主要思路是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)]