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

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

    Collection result = invoices.stream().collect(groupingBy(i -> i.month,
                    collectingAndThen(
                        reducing((Invoice i1, Invoice i2) -> new Invoice(i1.month, i1.amount + i2.amount)),
                            Optional::get))).values();
    

提交回复
热议问题