【Stream流】高级用法—分组求和、组合排序、求极值

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/cxh6863/article/details/102650492

通过上一遍博客(https://blog.csdn.net/cxh6863/article/details/102634781),对Stream的基础使用,大家应该对Stream流已经不再陌生,接下来学习下Stream的高级用法吧。

一、分组求和—collect

场景:

在一个班级,每个人都有自己的分数,怎样在java中使用代码对所有人的分数根据性别分类,然后进行求和。

方法:

使用collect方法将list收集成map,然后使用groupby分类,
getSum()——获取和
getMax()——获取最大值
getMin()——获取最小值
getAverage()——获取平均值
getCount()——获取数据量

使用:

System.out.println("分组求和:");
Map<String, IntSummaryStatistics> collectGroupBySex = students.stream().collect(Collectors.groupingBy(student::getSex, Collectors.summarizingInt(student::getScore)));
System.out.println("男生:"+collectGroupBySex.get("男"));
System.out.println("男生的分数和:"+collectGroupBySex.get("男").getSum());
System.out.println("男生中最大分数:"+collectGroupBySex.get("男").getMax());
System.out.println("男生中最小分数:"+collectGroupBySex.get("男").getMin());
System.out.println("男生中平均分数:"+collectGroupBySex.get("男").getAverage());
System.out.println("男生个数:"+collectGroupBySex.get("男").getCount());

运行结果

在这里插入图片描述

二、组合排序—comparing—>thenComparing

场景:

在一个班级,每个人都有自己的分数,怎样在java中使用代码对所有人的分数先根据性别排序再根据分数排序。

方法:

comparing,thenComparing

使用

System.out.println("组合排序:");
System.out.println("第一种:");
List<student> collectSortedMore = students.stream().sorted(Comparator.comparing(student::getSex).reversed().thenComparing(student::getScore).reversed()).collect(Collectors.toList());
collectSortedMore.stream().forEach(System.out::println);
System.out.println("第二种:");
students.sort(Comparator.comparing(student::getSex).reversed().thenComparing(student::getScore).reversed());
students.stream().forEach(student -> System.out.println(student));

运行结果

在这里插入图片描述

三、求极值—summarizingLong/summarizingInt

场景:

在一个班级,每个人都有自己的分数,怎样在java中使用代码求这个班级的平均分、最大分、最小分。

方法:

先使用summarizingLong和summarizingInt对分数汇总,接着分别获取极值

获取平均值——getAverage()
获取最大值——getMax()
获取最小值——getMin()
获取总分——getSum()
获取个数——getCount()

使用

System.out.println("求极值:");
LongSummaryStatistics collectStudentsSummary = students.stream().collect(Collectors.summarizingLong(student::getScore));
System.out.println("平均值=" + collectStudentsSummary.getAverage());
System.out.println("个数=" + collectStudentsSummary.getCount());
System.out.println("最大值=" + collectStudentsSummary.getMax());
System.out.println("最小值=" + collectStudentsSummary.getMin());
System.out.println("总和=" + collectStudentsSummary.getSum());

运行结果

在这里插入图片描述

最后关于stream和for,以下是个人理解:
stream和for循环的比较
for循环是对某一个操作循环依次执行
stream是对某一个操作异步执行
也就是说for循环是这一次操作结束了,再进行下一次执行这个操作
而stream是几乎同时进行所有操作
比如对某个操作需要循环十次,for循环是一次一次执行,执行10次,stream是10次同时进行,执行10次。

猜你喜欢

转载自blog.csdn.net/cxh6863/article/details/102650492
今日推荐