Java 8 stream - merge collections of objects sharing the same Id

后端 未结 6 1673
后悔当初
后悔当初 2021-02-13 15:11

I have a collection of invoices :

class Invoice {
  int month;
  BigDecimal amount
}

I\'d like to merge these invoices, so I get one invoice pe

6条回答
  •  借酒劲吻你
    2021-02-13 16:11

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

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

    If you really need a 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())));
    

    Both obviously assume that Invoice is mutable...

提交回复
热议问题