例:
先写一个类
public class Student {
private Integer id;
private String name;
private String sex;
private Integer age;
private Integer classNumber;//班级
随便造几条数据,放到List里面
public static void main(String[] args) {
List<Student> studentList = new ArrayList<Student>();
studentList.add(new Student(1, "张", "男", 20, 2));
studentList.add(new Student(2, "李", "男", 21, 1));
studentList.add(new Student(3, "王", "女", 19, 1));
studentList.add(new Student(4, "赵", "男", 19, 1));
studentList.add(new Student(5, "杰", "男", 20, 2));
}
对班级进行分组
Map<Integer, List<Student>> studentGroup = studentList.stream().collect(Collectors.groupingBy(Student::getClassNumber));
for(Map.Entry<Integer, List<Student>> entry : studentGroup.entrySet()){
System.out.println("key :"+entry.getKey()+", value :"+entry.getValue());
}
结果如下:
key :1, value :[Student(id=2, name=李, sex=男, age=21, classNumber=1), Student(id=3, name=王, sex=女, age=19, classNumber=1), Student(id=4, name=赵, sex=男, age=19, classNumber=1)]
key :2, value :[Student(id=1, name=张, sex=男, age=20, classNumber=2), Student(id=5, name=杰, sex=男, age=20, classNumber=2)]