使用Lambda表达式 .groupingBy函数进行分组

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;

import com.example.demo.Demo.dto.Student;

import java.util.*;
import java.util.stream.Collectors;

public class map {
    public static void main(String[] args) {
        Student stu1 = new Student();
        stu1.setId(1);
        stu1.setName("张三");
        stu1.setDate(String.valueOf(new Date()));

        Student stu2 = new Student();
        stu2.setId(2);
        stu2.setName("李四");
        stu2.setDate(String.valueOf(new Date()));

        Student stu3 = new Student();
        stu3.setId(2);
        stu3.setName("李四02");
        stu3.setDate(String.valueOf(new Date()));

        //装载学生类
        List<Student> stuList = new ArrayList<>();
        Collections.addAll(stuList, stu1, stu2, stu3);

        Assert.isTrue(stuList.size() > 0, "当前集合为空");

        Map<Integer, List<Student>> map = stuList.stream().collect(Collectors.groupingBy(Student::getId));

        map.forEach((key, value) -> {
            System.out.println(key + ", 分组之后的值:" + JSON.toJSON(value));
        });
        /*1, 分组之后的值:[{"date":"Fri Jul 23 09:58:26 CST 2021","name":"张三","id":1}]*/
        /*2, 分组之后的值:[{"date":"Fri Jul 23 09:58:26 CST 2021","name":"李四","id":2},{"date":"Fri Jul 23 09:58:26 CST 2021","name":"李四02","id":2}]*/
    }
}
上一篇:标题Lambda表达式的使用,集合元素排序,如果按工资降序排序,如果工资相同,按年龄升序排序,如果年龄相同,按姓名排序


下一篇:面向对象编程