Java List集合进行分组

例:

先写一个类

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)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值