1、list实体集合根据某个属性分组后求和
方法一:
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());
方法二: 文章来源:https://www.toymoban.com/news/detail-676379.html
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));
例子:文章来源地址https://www.toymoban.com/news/detail-676379.html
@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));
}
到了这里,关于Java8新特性整理记录的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!