Stream 查找与约束匹配
Stream 查找与约束匹配
函数
anyMatch(lambda表达式) 有任意满足lambda表达式的元素则返回true,否则返回false
allMatch(lambda表达式) 若所有表达式都满足lambda表达式则返回true,否则返回false
findFirst() 返回满足filter条件的第一个元素,存在则返回,否则抛异常
findAny() 返回满足filter条件的任意一个元素,存在则返回,否则抛异常
isPresent() 存在则返回true,否则返回false
ifPresent(lambda表达式) 存在则执行lambda表达式,否则不执行
实践
@Test
public void test8() {
Employee e1 = new Employee(1, 21, "zhangsan", "F");
Employee e2 = new Employee(2, 45, "lisi", "M");
Employee e3 = new Employee(3, 60, "wangwu", "M");
Employee e4 = new Employee(4, 32, "zhouliu", "F");
Employee e5 = new Employee(5, 28, "zhaoqi", "M");
Employee e6 = new Employee(6, 43, "qianba", "F");
List<Employee> list = Arrays.asList(e1, e2, e3, e4, e5, e6);
boolean b = list.stream().anyMatch(e -> e.getAge() > 58);
System.out.println(b);
boolean b1 = list.stream().allMatch(e -> e.getAge() > 58);
System.out.println(b1);
Optional<Employee> first = list.stream().filter(e -> e.getAge() > 40).findFirst();
System.out.println(first.get());
// 抛异常
// Optional<Employee> first1 = list.stream().filter(e -> e.getAge() > 80).findFirst();
// System.out.println(first1.get());
Optional<Employee> any = list.stream().filter(e -> e.getAge() > 40).findAny();
System.out.println(any.get());
boolean present = list.stream().filter(e -> e.getAge() > 40).findFirst().isPresent();
System.out.println(present);
list.stream().filter(e -> e.getAge() > 40).findFirst().ifPresent(System.out::println);
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?