按两个字段分组,然后对BigDecimal求和 [英] Group by two fields then summing BigDecimal

查看:726
本文介绍了按两个字段分组,然后对BigDecimal求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张税单:

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:

I would like to combine them base on unique title and rate, then add the price, expected:

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

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

How can I do this in Java 8?

在Java 8中按多个字段名称分组,不是对一个字段求​​和,它只能按两个字段进行分组. /p>

Group by multiple field names in java 8, is not summing a field, it can only group by the two fields.

推荐答案

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

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

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

这篇关于按两个字段分组,然后对BigDecimal求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆