I have a List<LedgerEntry> ledgerEntries
and I need to calculate the sums of creditAmount and debitAmount.
class LedgerEntry{
private BigDecimal creditAmount;
private BigDecimal debitAmount;
//getters and setters
}
I have implemented this as,
BigDecimal creditTotal = ledgeredEntries.stream().map(p ->p.getCreditAmount()).
reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal debitTotal = ledgeredEntries.stream().map(p ->p.getDebitAmount()).
reduce(BigDecimal.ZERO, BigDecimal::add);
//...
//Use creditTotal, debitTotal later
This looks like I'm iterating over the List twice. Is there a way to get this done in one go without having to steam the list twice?
Pre Java 8 version
BigDecimal creditTotal = BigDecimal.ZERO;
BigDecimal debitTotal = BigDecimal.ZERO;
for(LedgerEntry entry : ledgerEntries){
creditTotal = creditTotal.add(entry.getCreditAmount());
debitTotal = debitTotal.add(entry.getDebitAmount());
}
BigDecimal
s are immutable) more readable and maintainable (and probabably more performant) than any stream solution which tries to calculate the two sums at once. – Occultism.filter(LedgerEntry::getCreditAmount)
to use method references for the lambdas. – Anesthetize