我有一张税单:

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

我想将它们基于唯一的titlerate组合起来,然后添加price:
 TaxLine = title:"New York Tax", rate:0.20, price:40.00
 TaxLine = title:"County Tax", rate:0.10, price:10.00

如何在Java 8中做到这一点?

Group by multiple field names in java 8,不对字段求和,只能按两个字段分组。

最佳答案

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

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());

07-26 01:54