上期我們討論了java Stream的一些操作,這期我們繼續最後一期。
Collector 工具庫:Collectors
Student s1 = new Student("aa", "aa");
Student s2 = new Student("bb", "30");
Student s3 = new Student("cc","20");
List<student> list = Arrays.asList(s1, s2, s3);
//裝成list
List<integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList()); // [10, 20, 10]
//轉成set
Set<integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet()); // [20, 10]
//轉成map,注:key不能相同,否則報錯
Map<string> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
// {cc=10, bb=20, aa=10}
//字符串分隔符連接
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")"));
// (aa,bb,cc)
聚合操作
//1.學生總數
Long count = list.stream().collect(Collectors.counting()); // 3
//2.最大年齡 (最小的minBy同理)
Integer maxAge = list.stream().map(Student::getAge).collect(Collectors.maxBy(Integer::compare)).get();
// 20
//3.所有人的年齡
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge));
// 40
//4.平均年齡
Double averageAge = list.stream().collect(Collectors.averagingDouble(Student::getAge));
// 13.333333333333334
// 帶上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(Student::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
//分組
Map<integer>> ageMap = list.stream().collect(Collectors.groupingBy(Student::getAge));
//多重分組,先根據類型分再根據年齡分
Map<integer>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(Student::getType, Collectors.groupingBy(Student::getAge)));
//分區
//分成兩部分,一部分大於10歲,一部分小於等於10歲
Map<boolean>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
//規約
Integer allAge = list.stream().map(Student::getAge).collect(Collectors.reducing(Integer::sum)).get(); //40
/<boolean>/<integer>/<integer>/<string>/<integer>/<integer>/<student>
好的,到這裡我的javaStream就寫完了,我以前也不會這些,現在基本上就是我看一遍,敲一遍,再放上來,下一期學習什麼我還沒用想好。
閱讀更多 LOVER 的文章