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());
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM