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}]*/
        }
    }
    
  • 相关阅读:
    2-6 求阶乘序列前N项和
    2-5 求平方根序列前N项和
    2-4 求交错序列前N项和
    2-3 求平方与倒数序列的部分和
    2-2 阶梯电价
    2-1 求整数均值
    2-17 生成3的乘方表
    【秋招之行】自白篇
    Django开发个人博客入门学习经验贴
    浅尝装饰器和AOP
  • 原文地址:https://www.cnblogs.com/Twittery/p/15047660.html
Copyright © 2011-2022 走看看