/***@authorindex
* @date 2020/10/27
**/
public classTestcollectingAndThen {
@Testpublic voidtest(){final int NUM = 14;
List peopleList = new ArrayList<>(NUM);
String[] names= {"小張", "小龍", "小牛", "小豬", "小黑", "小紅", "小白"};for (int i = 0; i < 5; i++) {//添加5個19歲的隨機性別和名字的小朋友
peopleList.add(new People(19, (int) (Math.random() * 2), names[(int) (Math.random() *names.length)]));
}for (int i = 5; i < 8; i++) {//添加3個31歲的隨機性別和名字的小朋友
peopleList.add(new People(31, (int) (Math.random() * 2), names[(int) (Math.random() *names.length)]));
}for (int i = 8; i < NUM; i++) {//添加6個22歲的隨機性別和名字的小朋友
peopleList.add(new People(22, (int) (Math.random() * 2), names[(int) (Math.random() *names.length)]));
}//collectingAndThen先對stream里的元素進行collecting,之后再對結果進行操作,//下面的結果是一個map,對map計算元素數目
System.out.println("分組數目:");
Integer groupCount=peopleList.stream().collect(
Collectors.collectingAndThen(Collectors.groupingBy(People::getName), Map::size));
System.out.println(groupCount);
System.out.println("-------------------------------------");//按照名字分組
System.out.println("按照名字分組");
System.out.println(
peopleList.stream().collect(Collectors.groupingBy(People::getName))
);
System.out.println("-------------------------------------");//按照名字分組(分組的結果是一個map),并統計每一個分組(map中的每一個value)中的元素數目
System.out.println("統計每一個分組(map中的每一個value)中的元素數目");
System.out.println(
peopleList.stream().collect(Collectors.groupingBy(People::getName, Collectors.counting()))
);
System.out.println("-------------------------------------");//按照名字分組(分組的結果是一個map),并取出每一組的最大值
System.out.println("取出每一組的最大值");
System.out.println(
peopleList.stream().collect(Collectors.groupingBy(People::getName, Collectors.maxBy(new Comparator() {
@Overridepublic intcompare(People o1, People o2) {return o1.getAge() -o2.getAge();
}
})))
);
}
}