其他分享
首页 > 其他分享> > 使用Lambda表达式 .groupingBy函数进行分组

使用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}]*/
    }
}

标签:stu2,stu3,stu1,groupingBy,分组,Student,import,new,Lambda
来源: https://www.cnblogs.com/Twittery/p/15047660.html