首页 > 解决方案 > 如何在 java 8 的 forEach 中使用方法引用测试 Predicate

问题描述

我正在尝试 forEach 中的方法参考

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

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

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

标签: javalambdajava-8method-reference

解决方案


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

people.stream().filter(predicate).forEach(p -> System.out.println("Print here"));

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


推荐阅读