java - 如何在 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");}
});
}
解决方案
您应该能够在运行操作之前过滤列表:
people.stream().filter(predicate).forEach(p -> System.out.println("Print here"));
你不能使用if(predicate::test)
,因为if
需要一个布尔表达式(predicate::test
这里甚至不知道类型 - 检查 lambda 表达式的目标类型文档)。使其工作的唯一方法是test()
像在第一个代码段中那样调用该方法。
推荐阅读
- django - 在 Django 中向用户添加对象
- android - 如何将电子邮件数据写入 NFC 标签?
- mysql - 订阅即将到期时如何通知用户?设计和架构建议
- javascript - 在不刷新页面的情况下刷新日历数据 Div
- reporting-services - 电子邮件订阅服务失败 - SSRS
- paypal - 贝宝订阅套餐试用设置
- c# - 如何在我的 Azure 函数上修复此 502 错误?
- autohotkey - 使用 AutoHotKey ControlSend 访问 MDI 工具栏菜单
- r - 将 image.plot 的连续图例转换为离散图例
- vba - 有没有办法在打开时更改 Ms Access 对话框窗体的属性?