按两个字段分组,然后对BigDecimal求和

问题描述

主体与链接问题中的主体相同,只需要一个不同的下游收集器来求和:

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