目录
Stream流的聚合和收集
1. Stream的聚合操作count、max
2. Stream的分组操作partitioningBy
代码示例
计数(count):统计语文分数大于70的学生人数
最大值(max):找出数学分数最高的学生姓名
分组(partitioningBy):学生的语文分数是否大于80分
总结
Stream流的聚合和收集
继续Stream流的两个重要概念:聚合和收集。这些是在处理集合数据时非常强大的工具,能够更轻松地进行数据操作。
1. Stream的聚合操作count、max
在Stream流中,count()
方法用于计算流中元素的数量,而max()
方法用于获取流中的最大元素。这些函数将集合的元素聚合成单一的结果。
2. Stream的分组操作partitioningBy
分组函数是一类用于根据某个条件将元素分为不同组的操作。partitioningBy()
方法是Stream流中的一种分组函数,它根据指定的条件将流中的元素分为满足条件和不满足条件两组。这种方式产生的结果是一个Map对象,其中包含两个键值对,分别对应满足条件和不满足条件的元素集合。
代码示例
实际操作一下。现在,我们将通过一个学生实体类,其中包含年龄、姓名和四门学科的分数。
public class Student {
private String name;
private int age;
private int chineseScore;
private int mathScore;
private int englishScore;
private int physicsScore;
// 构造函数和getter省略
}
计数(count):统计语文分数大于70的学生人数
// 使用for循环
int count = 0;
for (Student student : studentList) {
if (() > 70) {
count++;
}
}
// 使用Stream流
long count = ()
.filter(student -> () > 70)
.count();
for循环需要创建一个变量,一个一个得加才能得出,stream流直接一个count()
最大值(max):找出数学分数最高的学生姓名
// 使用for循环
int maxMathScore = Integer.MIN_VALUE;
String topMathStudent = "";
for (Student student : studentList) {
if (() > maxMathScore) {
maxMathScore = ();
topMathStudent = ();
}
}
// 使用Stream流
Optional<String> topMathStudent = ()
.max((Student::getMathScore))
.map(Student::getName);
for循环需要创建两个变量,并且要边循环边判断,逻辑需要自己写,stream流直接一个max()
分组(partitioningBy):学生的语文分数是否大于80分
// 使用for循环
Map<Boolean, List<Student>> partitionedMap = new HashMap<>();
List<Student> excellentStudents = new ArrayList<>();
List<Student> otherStudents = new ArrayList<>();
for (Student student : studentList) {
if (() > 80) {
(student);
} else {
(student);
}
}
(true, excellentStudents);
(false, otherStudents);
// 使用Stream流的partitioningBy
Map<Boolean, List<Student>> partitionedMapStream = ()
.collect((student -> () > 80));
这里就很明显了,stream流只用了两行就完成了分组筛选
总结
在使用for循环和Stream流分别实现这三个逻辑时,我们可以总结出Stream流的一些优势:
-
简洁性: Stream流提供了更为简洁的语法,减少了样板代码,使代码更易读。
-
并行处理: Stream流天然支持并行处理,能够充分发挥多核处理器的性能,提高程序的运行效率。
-
延迟执行: Stream流具有延迟执行的特性,只有在需要结果的时候才会执行计算,避免了不必要的性能开销。
推荐阅读:
面试官:会用stream流筛选数据么?只会for循环?
我第一次使用AI写了一篇文章
Navicat激活(2024.01.13有效)
ArrayList(源码分析)—面试经典问题
SpringBoot-AOP深入浅出通俗易懂
最后我还整理汇总了⼀些 Java ⾯试相关的⾼质量 PDF 资料和免费Idea账号
公众号:Java小白,回复“⾯试” 和“idea破解”即可获取!