一尘不染

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

java

我有一张税单:

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;
}

我想基于unique title和合并它们rate,然后添加price预期:

 TaxLine = title:"New York Tax", rate:0.20, price:40.00
 TaxLine = title:"County Tax", rate:0.10, price:10.00

阅读 568

收藏
2020-12-03

共1个答案

一尘不染

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

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());
2020-12-03