问题描述
主体与链接问题中的主体相同,只需要一个不同的下游收集器来求和:
List<TaxLine> flattened = 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());
解决方法
我有一张税单:
TaxLine = title:"New York Tax",rate:0.20,price:20.00
TaxLine = title:"New York Tax",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;
}
我想基于unique title
和合并它们rate
,然后添加price
预期:
TaxLine = title:"New York Tax",price:40.00
TaxLine = title:"County Tax",price:10.00