我有一份税单:
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
Run Code Online (Sandbox Code Playgroud)
TaxLine类是
public class TaxLine {
private BigDecimal price;
private BigDecimal rate;
private String title;
}
Run Code Online (Sandbox Code Playgroud)
我想将它们结合起来的基础上独一无二的title和rate,然后加入price,预计:
TaxLine = title:"New York Tax", rate:0.20, price:40.00
TaxLine = title:"County Tax", rate:0.10, price:10.00
Run Code Online (Sandbox Code Playgroud)
我怎样才能在Java 8中做到这一点?
在java 8中按多个字段名分组,不是对一个字段求和,它只能由两个字段组合.
shm*_*sel 10
主体与链接问题中的相同,您只需要一个不同的下游收集器来总结:
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());
Run Code Online (Sandbox Code Playgroud)