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

后端 未结 6 1670
后悔当初
后悔当初 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:13

    Here is the solution by My library: AbacusUtil

    Stream.of(invoices)
          .groupBy2(Invoice::getMonth, Invoice::getAmount, BigDecimal::add)  
          .map(e -> new Invoice(e.getKey(), e.getValue())) // Probably we should not modify original invoices. create new instances.
          .toList();
    

提交回复
热议问题