如何在java 8的forEach中使用方法引用测试Predicate

Jav*_*der 2 java lambda java-8 method-reference

我正在尝试 forEach 内部的方法引用

private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
    people.forEach(p-> { if (predicate.test(p)){
        System.out.println("Print here");}
    });
}
Run Code Online (Sandbox Code Playgroud)

以上工作正常,但我想使用方法参考使它更短,但是它给出了编译问题。有什么办法让它发生?

private static void printConditionally8(List<Person> people, Predicate<Person> predicate) {
    people.forEach({ if (predicate::test){
        System.out.println("Print here");}
     });
}
Run Code Online (Sandbox Code Playgroud)

ern*_*t_k 6

您应该能够在运行操作之前过滤列表:

people.stream().filter(predicate).forEach(p -> System.out.println("Print here"));
Run Code Online (Sandbox Code Playgroud)

您不能使用if(predicate::test)因为if采用布尔表达式(predicate::test此处甚至不知道的类型- 检查 lambda 表达式的目标类型文档)。使其工作的唯一方法是test()像在第一个代码段中那样调用该方法。