You can reduce to a record of totals:
LedgerEntry totalsEntry = entries.stream().reduce(new LedgerEntry(), (te, e) -> { te.setCreditAmount(te.getCreditAmount().add(e.getCreditAmount())); te.setDebitAmount(te.getDebitAmount().add(e.getDebitAmount())); return te; });
Update
The comments correctly pointed out that reduce() should not change the initial value of the identifier and that collect() should be used for mutable reductions. Below is the version using collect() (using the same BiConsumer for both battery and combiner). It also considers potential creditAmount if creditAmount and / or debitAmount not set.
BiConsumer<LedgerEntry, LedgerEntry> ac = (e1, e2) -> { BigDecimal creditAmount = e1.getCreditAmount() != null ? e1.getCreditAmount() : BigDecimal.ZERO; BigDecimal debitAmount = e1.getDebitAmount() != null ? e1.getDebitAmount() : BigDecimal.ZERO; e1.setCreditAmount(creditAmount.add(e2.getCreditAmount())); e1.setDebitAmount(debitAmount.add(e2.getDebitAmount())); }; LedgerEntry totalsEntry = entries.stream().collect(LedgerEntry::new, ac, ac);
The flash version of pre-Java 8 is starting to look attractive.
Robby cornelissen
source share