• Java lambda 分组后多列求和


    主要思路是reducing,可以像sql一样分组后多列求和处理成新对象等;

    select code,max(name)as name,sum(chengJi)as chengJi,sum(age)as age,sum(value)as value from student group by code 

    将上边sql翻译成java 后为如下代码

    @Data
        public class Student{
            public Student() {
            }
    
            public Student(String code, String name, Long chengJi, Integer age, BigDecimal value) {
                this.code = code;
                this.name = name;
                this.chengJi = chengJi;
                this.age = age;
                this.value = value;
            }
    
            private String code;
            private String name;
            private Long chengJi;
            private Integer age;
            private BigDecimal value;
    
        }
        @Test
        public void lambda() {
            List<Student> studentList = new ArrayList();
            studentList.add(new Student("a","am",1L,2,new BigDecimal(3)));
            studentList.add(new Student("a","am1",1L,2,new BigDecimal(3)));
            studentList.add(new Student("b","bm1",1L,2,new BigDecimal(3)));
            List<Student> collect = studentList.stream().collect(Collectors.groupingBy(Student::getCode,
                    Collectors.reducing((sum, s) ->
                            new Student(s.code, s.name, sum.chengJi + sum.chengJi,
                                    sum.age + s.age, sum.value.add(s.value)))
            )).entrySet().stream().map(c -> c.getValue().get()).collect(Collectors.toList());
            System.out.println(collect);
        }

    打印结果:

    [OtherTest.Student(code=a, name=am1, chengJi=2, age=4, value=6), OtherTest.Student(code=b, name=bm1, chengJi=1, age=2, value=3)]

  • 相关阅读:
    在ConcurrentModificationException异常上的联想
    记录一下自己爬虎牙LOL主播的爬虫思路
    ajax解决跨域问题
    解决多线程下数据库操作问题
    浅谈时间复杂度
    想一下,最大公约数怎么求
    IO流与IO缓冲
    循环移位
    3Sum探讨(Java)
    Two Sum(两个数的相加)
  • 原文地址:https://www.cnblogs.com/stjwy/p/14074175.html
Copyright © 2020-2023  润新知