Group by two fields then summing BigDecimal

后端 未结 3 961
轮回少年
轮回少年 2021-02-04 11:19

I have a list of taxes:

TaxLine = title:\"New York Tax\", rate:0.20, price:20.00
TaxLine = title:\"New York Tax\", rate:0.20, price:20.00
TaxLine = title:\"Count         


        
3条回答
  •  伪装坚强ぢ
    2021-02-04 12:15

    The principle is the same as in the linked question, you just need a different downstream collector to sum:

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

提交回复
热议问题