java8流式操作实现集合分组聚合
在日常的开发中,因为每次使用java8的流式操作给自己带来了极大的便利,但是一直局限于最基本的流式操作,当在开发中遇到了这样的一个场景:对一个集合中根据其中的属性对象中的属性来进行分组,然后统计分组后的某字段的数据总和,我发现我每次都需要使用多次流式操作才能完成,第一是先通过属性分组成一个map,然后在对map进行流式操作来获取数据总和。
这样写的很不优雅,但是java8早就为我们考虑到了这一点,通过一次流式代码便可完成。废话不多说,代码如下:
public class StreamTest {
public static void main(String[] args) {
Person person = new Person();
person.setName("bibi");
person.setPrice(new BigDecimal(12.31));
Person person1 = new Person();
person1.setName("bibi");
person1.setPrice(new BigDecimal(15.58));
Person person2 = new Person();
person2.setName("xixi");
person2.setPrice(new BigDecimal(17.52));
Person person3 = new Person();
person3.setName("lala");
person3.setPrice(new BigDecimal(5.26));
List<Person> list = new ArrayList<>(4);
list.add(person);
list.add(person1);
list.add(person2);
list.add(person3);
Map<String, BigDecimal> map = list.stream().collect(Collectors.groupingBy(Person::getName,
Collectors.collectingAndThen(Collectors.toList(), collections -> {
BigDecimal price = collections.stream().map(t -> t.getPrice()).reduce(BigDecimal.ZERO, BigDecimal::add);
return price;
})));
System.out.println(map);
}
}
分组后的结果为 :
