stream分组
1、根据集合元素中的一个属性值分组
Person p1 = new Person("张三", new BigDecimal("10.0"));
Person p2 = new Person("王五", new BigDecimal("10.0"));
Person p3 = new Person("李四", new BigDecimal("10.0"));
Person p4 = new Person("李四", new BigDecimal("10.0"));
Person p5 = new Person("张三", new BigDecimal("10.0"));
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(person -> person.getName()));
System.out.println(collect);
打印结果:
{李四=[{name='李四', salary=10.0}, {name='李四', salary=10.0}], 张三=[{name='张三', salary=10.0}, {name='张三', salary=10.0}], 王五=[{name='王五', salary=10.0}]}
2、分组求和
Person p1 = new Person("张三", new BigDecimal("10.0"));
Person p2 = new Person("王五", new BigDecimal("10.0"));
Person p3 = new Person("李四", new BigDecimal("10.0"));
Person p4 = new Person("李四", new BigDecimal("10.0"));
Person p5 = new Person("张三", new BigDecimal("10.0"));
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
Map<String, List<Person>> collect = list.stream().collect(Collectors.groupingBy(Person::getName));
List<Map<String,Object>> l = new ArrayList<>();
collect.entrySet().forEach(item->{
Map<String,Object> map = new HashMap<>();
map.put("title",item.getKey());
BigDecimal totalSalary = item.getValue().stream().map(Person::getSalary).reduce(BigDecimal.ZERO, BigDecimal::add);
map.put("totalSalary",totalSalary);
map.put("info",item.getValue());
l.add(map);
});
System.out.println(l);
打印结果:
[
{totalSalary=20.0, title=李四, info=[{name='李四', salary=10.0}, {name='李四', salary=10.0}]},
{totalSalary=20.0, title=张三, info=[{name='张三', salary=10.0}, {name='张三', salary=10.0}]},
{totalSalary=10.0, title=王五, info=[{name='王五', salary=10.0}]}
]
纸上得来终觉浅,绝知此事要躬行。