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
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)
));