zoukankan      html  css  js  c++  java
  • 使用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}]*/
        }
    }
    
  • 相关阅读:
    CF869E The Untended Antiquity 解题报告
    Walk 解题报告
    CF911F Tree Destruction 解题报告
    P4397 [JLOI2014]聪明的燕姿
    洛谷 P2329 [SCOI2005]栅栏 解题报告
    洛谷 P3747 [六省联考2017]相逢是问候 解题报告
    set-erase
    set-empty
    set-empty
    set-end
  • 原文地址:https://www.cnblogs.com/Twittery/p/15047660.html
Copyright © 2011-2022 走看看