Java 8流-合并共享相同ID的对象的集合 [英] Java 8 stream - merge collections of objects sharing the same Id

查看:831
本文介绍了Java 8流-合并共享相同ID的对象的集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有发票的集合:

class Invoice {
  int month;
  BigDecimal amount
}

我想合并这些发票,所以我每个月收到一张发票​​,金额是该月发票金额的总和.

I'd like to merge these invoices, so I get one invoice per month, and the amount is the sum of the invoices amount for this month.

例如:

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流?

How can I do this with java 8 streams?

由于我的Invoice类是可变的,修改它们不是问题,所以我选择了Eugene的解决方案

EDIT : as my Invoice class was mutable and it was not a problem to modify them, I choosed Eugene's solution

Collection<Invoice>  invoices = list.collect(Collectors.toMap(Invoice::getMonth, Function.identity(), (left, right) -> {
                left.setAmount(left.getAmount().add(right.getAmount()));
                return left;
            })).values();

推荐答案

如果您可以返回Collection,它将看起来像这样:

If you are OK returning a Collection it would look like this:

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是可变的...

Both obviously assume that Invoice is mutable...

这篇关于Java 8流-合并共享相同ID的对象的集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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