按两个字段分组,然后对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;

}

我想基于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

回答:

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

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求和 的全部内容, 来源链接: utcz.com/qa/420399.html

回到顶部