Lambdas(五) stream的操作集合
-
简介
结合前几节所讲到的,stream可以进行一系列类似SQL的操作。它本质与Collections有很大区别,总结一下:- Collections是将数据直接加载到内存中,Stream是只加载要处理的数据
- Stream对多核CPU进行了优化,Collections并没有
-
如何使用
背景参见第一节内容
//得到平局分数大于60的学生,按照名字排序
List<Student> list = studentQueryService.getStudentList().stream().filter(s -> s.getAvgScore() > 60)
.sorted(comparing(Student::getCnName))
.collect(toList());
//返回所有学生名字符串,名字排序后,用“,”分割
String str = studentQueryService.getStudentList().stream().map(s -> s.getCnName())
.sorted()
.distinct()
.reduce("", (a, b) -> a + b + ", ");
//是否存在年龄小于18岁的学生
boolean isExist = studentQueryService.getStudentList().stream().anyMatch(s -> s.getAge() < 18);
//打印年龄小于18岁的学生姓名
studentQueryService.getStudentList().stream().filter(s -> s.getAge() < 18)
.map(Student::getCnName)
.forEach(System.out::println);
//得到最高的平均分
Optional<Double> highestAvgScore = studentQueryService.getStudentList().stream()
.map(Student::getAvgScore)
.reduce(Double::max);
//Optional<T>可以有个默认值,在没有最大值的情况下
highestAvgScore.orElse(1d);
//得到平均分最小的学生记录
studentQueryService.getStudentList().stream()
.reduce((a, b) -> a.getAvgScore() < b.getAvgScore() ? a : b);
//得到平均分最小的学生记录 更好的操作
studentQueryService.getStudentList().stream()
.min(comparing(Student::getAvgScore));