我有一份税单:
TaxLine = title:"New York Tax", rate:0.20, price:20.00 TaxLine = title:"New York Tax", rate:0.20, price:20.00 TaxLine = title:"County Tax", rate:0.10, price:10.00
TaxLine类是
public class TaxLine { private BigDecimal price; private BigDecimal rate; private String title; }
我想将它们结合起来的基础上独一无二的title
和rate
,然后加入price
,预计:
TaxLine = title:"New York Tax", rate:0.20, price:40.00 TaxLine = title:"County Tax", rate:0.10, price:10.00
我怎样才能在Java 8中做到这一点?
在java 8中按多个字段名分组,不是对一个字段求和,它只能由两个字段组合.
主体与链接问题中的相同,您只需要一个不同的下游收集器来总结:
Listflattened = taxes.stream() .collect(Collectors.groupingBy( TaxLine::getTitle, Collectors.groupingBy( TaxLine::getRate, Collectors.reducing( BigDecimal.ZERO, TaxLine::getPrice, BigDecimal::add)))) .entrySet() .stream() .flatMap(e1 -> e1.getValue() .entrySet() .stream() .map(e2 -> new TaxLine(e2.getValue(), e2.getKey(), e1.getKey()))) .collect(Collectors.toList());