我有发票的集合:
class Invoice {
int month;
BigDecimal amount
}
我想合并这些发票,所以我每个月收到一张发票,金额是该月发票金额的总和。
例如:
invoice 1 : {month:1,amount:1000}
invoice 2 : {month:1,amount:300}
invoice 3 : {month:2,amount:2000}
输出:
invoice 1 : {month:1,amount:1300}
invoice 2 : {month:2,amount:2000}
我该如何使用Java 8流?
编辑:由于我的发票类是可变的,修改它们不是问题,所以我选择了尤金的解决方案
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
最佳答案
如果可以,则返回Collection
,如下所示:
Collection<Invoice> invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
})).values();
如果您确实需要
List
: list.stream().collect(Collectors.collectingAndThen(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
left.setAmount(left.getAmount().add(right.getAmount()));
return left;
}), m -> new ArrayList<>(m.values())));
两者显然都认为
Invoice
是可变的...