Stream分组和分区
分区是分组的一种
Student student1 = new Student("zhangsan",80,20);
Student student2 = new Student("lisi",90,30);
Student student3 = new Student("wangwu",90,40);
Student student4 = new Student("zhaoliu",70,20);
List<Student> students = Arrays.asList(student1,student2,student3,student4);
// 统计各个分数都有哪些学生
// 原始方法:
// 1、定义一个Map<Integer.List<Student>> 用来存放统计结果
// 2、循环遍历students
// 3、如果map中存在这个分数 这个分数对应的list就add 如果不存在map就put
/* Map<Integer,List<Student>> resultMap = new HashMap<>();
for (Student student : students) {
if (resultMap.containsKey(student.getScore())){
resultMap.get(student.getScore()).add(student);
continue;
}
List<Student> stuList = new ArrayList<Student>();
stuList.add(student);
resultMap.put(student.getScore(),stuList);
}
System.out.println(resultMap);*/
//用stream的方式
Map<Integer, List<Student>> collect1 = students.stream().collect(Collectors.groupingBy(student -> student.getScore()));
System.out.println(collect1);
// 统计大于80分和小于80分的
Map<Boolean, List<Student>> collect2 = students.stream().collect(Collectors.partitioningBy(student -> student.getScore() > 80));
System.out.println(collect2);