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

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

    You can do something like

        Map invoiceMap = invoices.stream()
                .collect(Collectors.groupingBy(                   // group invoices by month
                        invoice -> invoice.month
                ))
                .entrySet().stream()                              // once you have them grouped stream then again so...
                .collect(Collectors.toMap(
                        entry -> entry.getKey(),                  // we can mantain the key (month)
                        entry -> entry.getValue().stream()        // and streaming all month's invoices
                            .reduce((invoice, invoice2) ->        // add all the ammounts
                                    new Invoice(invoice.month, invoice.amount.add(invoice2.amount)))
                                .orElse(new Invoice(entry.getKey(), new BigDecimal(0)))          // In case we don't have any invoice (unlikeable)
                ));
    

提交回复
热议问题