具有多个参数的foreach中的函数引用

时间:2016-04-21 10:25:09

标签: java-8 method-reference

我有一些情况我希望传递一个方法的方法引用,该方法在forEach中有多个参数,我能够使用单个arg方法传递,这是执行(Map页面)但我不知道我怎样才能在forEach中传递execute(Map页面,Integer userInstanceId),需要帮助。

static List<Map<String,Object>> pages = new ArrayList<>();
static Map<String,Object> pageIdWithPageInstanceId = new HashMap<>();

public static void testMethodReference() {
    TestListMapLamda tt = new TestListMapLamda();
    Integer userInstanceId = 22;
    pages.stream().filter(page -> null != pageIdWithPageInstanceId.get(page.get("PageID"))).forEach( tt::execute);//this calling the single arg action which is execute(Map<String,Object> page) but not execute(Map<String,Object> page, Integer userInstanceId)       
}
public void execute(Map<String,Object> page) {
    page.put("UserInstanceID", 1111);
}

public void execute(Map<String,Object> page, Integer userInstanceId) {
    page.put("UserInstanceID", userInstanceId);
}

我可以通过以下代码调用execute(Map页面,Integer userInstanceId),但是我希望像一个参数方法引用一样有一些更紧凑的阶段。

    public static void testMethodReference2() {

    TestListMapLamda tt = new TestListMapLamda();
    Integer userInstanceId = 22;
    pages.stream().filter(page -> null != pageIdWithPageInstanceId.get(page.get("PageID"))).forEach( page -> {
        tt.execute(page, userInstanceId);
    });     

}

0 个答案:

没有答案