这一节主要演示lambda的几个查找与匹配元素的方法。
初始化测试数据:
//查找与匹配
List<Student> list = new ArrayList<>();
String[] names = {"小明","小华","小志","小东","小李","小张","小王","小周","小吴","小郑"};
for(int i=0; i<10; i++) {
Student student = Student.builder()
.name(names[i])
.age(12+i/5)
.no(i+1)
.math(85d+i).build();
list.add(student);
}
//初始化数据
System.out.println("======初始化数据:======");
list.forEach(System.out::println);
1、allMatch-只有流中所有元素都满足才返回true
boolean allMatch = list.stream().allMatch(x -> x.getMath() > 80);
System.out.println("allMatch所有学生数学成绩是否都大于80分:"+allMatch);
输出结果:
allMatch所有学生数学成绩是否都大于80分:true
2、anyMatch
boolean anyMatch = list.stream().anyMatch(x -> x.getMath() > 95);
System.out.println("anyMatch所有学生数学成绩是否存在大于95分:"+anyMatch);
输出结果:
anyMatch所有学生数学成绩是否存在大于95分:false
3、noneMatch
boolean noneMatch = list.stream().noneMatch(x -> x.getMath() > 95);
System.out.println("noneMatch所有学生数学成绩是否存在大于95分:"+noneMatch);
输出结果:
noneMatch所有学生数学成绩是否存在大于95分:true
4、findAny
Optional<Student> findAny = list.stream().filter(x -> x.getName().equals("小华")).findAny();
System.out.println("findAny-学生中名字是否有叫【小华】的:"+findAny.isPresent());
输出结果:
findAny-学生中名字是否有叫【小华】的:true
5、findFirst
Optional<Student> findFirst = list.stream().filter(x -> x.getName().equals("小华")).findFirst();
System.out.println("findFirst-学生中名字是否有叫【小华】的:"+findFirst.isPresent());
输出结果:
findFirst-学生中名字是否有叫【小华】的:true