1、list实体集合根据某个属性分组后求和
方法一:
java
list.stream().collect(Collectors.groupingBy(e -> e.getId())).values().stream().map(d -> {
DemoEntity sampleData = d.get(0);
sampleData.setPremium(d.stream().map(s -> new BigDecimal(s.getPremium())).reduce(BigDecimal.ZERO, BigDecimal::add).longValue());
return sampleData;
}).collect(Collectors.toList());
方法二:
List orderTwo = list.stream().collect(Collectors.toMap(DemoEntity::getId,e->e,(o1,o2)->{
o1.setPremium(o1.getPremium()+o2.getPremium());
return o1;
})).values().stream().collect(Collectors.toList());
System.out.println(JSON.toJSON(orderTwo));
例子:
java
@Data
public class DemoEntity {
private int id;
private Long premium;
}
运行main方法
public static void main(String[] args) {
List<DemoEntity> list = new ArrayList<>();
DemoEntity demo = new DemoEntity();
demo.setId(1);
demo.setPremium(23L);
DemoEntity demo1 = new DemoEntity();
demo1.setId(2);
demo1.setPremium(13L);
list.add(demo);
list.add(demo1);
List<DemoEntity> list1 = new ArrayList<>();
DemoEntity demo4 = new DemoEntity();
demo4.setId(1);
demo4.setPremium(12L);
DemoEntity demo5 = new DemoEntity();
demo5.setId(2);
demo5.setPremium(45L);
list1.add(demo4);
list1.add(demo5);
list.addAll(list1);
System.out.println(JSON.toJSON(list));
List orders = list.stream().collect(Collectors.groupingBy(e -> e.getId())).values().stream().map(d -> {
DemoEntity sampleData = d.get(0);
sampleData.setPremium(d.stream().map(s -> new BigDecimal(s.getPremium())).reduce(BigDecimal.ZERO, BigDecimal::add).longValue());
return sampleData;
}).collect(Collectors.toList());
System.out.println(JSON.toJSON(orders));
List orderTwo = list.stream().collect(Collectors.toMap(DemoEntity::getId,e->e,(o1,o2)->{
o1.setPremium(o1.getPremium()+o2.getPremium());
return o1;
})).values().stream().collect(Collectors.toList());
System.out.println(JSON.toJSON(orderTwo));
}