jdk8-》joining、groupingBy、summarizingInt函数

拼接函数 Collectors.joining
  // 3种重载方法
  Collectors.joining()
  Collectors.joining("拼接符")
  Collectors.joining("拼接符", "前缀", "后缀")
  String result = Stream.of("springboot", "mysql", "html5","css3").collect(Collectors.joining(",", "[", "]"));
 
分组函数 Collectors.groupingBy
Map<String, List<Student>> listMap = students.stream().collect(Collectors.groupingBy(obj -> obj.getProvince()));
key: 分组字段
value: 分组后的结果
 
listMap.forEach((key, value) -> {
  System.out.println("========");
  System.out.println(key);
  value.forEach(obj -> {
  System.out.println(obj.getAge());
  });
});
 
分组统计:聚合函数进⾏统计查询,分组后统计个数
Collectors.counting() 统计元素个数
 
案例:根据省份分组后,统计各省份的人数
Map<String, Long> listMap = students.stream().collect(Collectors.groupingBy(Student::getProvince, Collectors.counting()));
listMap.forEach((key, value) -> {System.out.println(key+"省⼈数有"+value);});
 
key: 分组字段
value: 统计个数
 
集合统计:
IntSummaryStatistics summaryStatistics =students.stream().collect(Collectors.summarizingInt(Student::getAge));
System.out.println("平均值:" + summaryStatistics.getAverage());
System.out.println("⼈数:" + summaryStatistics.getCount());
System.out.println("最⼤值:" + summaryStatistics.getMax());
System.out.println("最⼩值:" + summaryStatistics.getMin());
System.out.println("总和:" + summaryStatistics.getSum());
 
posted @ 2020-01-05 22:41  scwyfy  阅读(2313)  评论(0编辑  收藏  举报