Streams: calculate the difference of totals at a time

I have a List<LedgerEntry> ledgerEntries and I need to calculate the sum of creditAmount and debitAmount.

 class LedgerEntry{ private BigDecimal creditAmount; private BigDecimal debitAmount; //getters and setters } 

I 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); BigDecimal sumCreditDebit = creditTotal.subtract(debitTotal); 

Looks like I'm repeating List twice. Is there a way to do this at a time without skipping the list twice?

+5
source share
4 answers

You can subtract individual amounts in map and then sum with reduce

 ledgerEntries.stream() .map(e->e.getCreditAmount().subtract(e.getDebitAmount()) .reduce(0,BigDecimal::add); 
+4
source

Just reduce it to:

 BigDecimal sumCreditDebit = ledgeredEntries.stream().map(p -> p.getCreditAmount() .subtract(p.getDebitAmount())) .reduce(BigDecimal.ZERO, BigDecimal::add); 
+6
source
 BigDecimal result = ledgeredEntries.stream().map(p -> p.getCreditAmount().subtract(p.getDebitAmount())) .reduce(BigDecimal.ZERO, BigDecimal::add); 
+3
source

Here is my solution:

  BigDecimal result = array.stream().reduce(BigDecimal.ZERO, (bigDecimal, ledgerEntry) -> bigDecimal.add(ledgerEntry.getCreditAmount()).subtract(ledgerEntry.getDebitAmount()), BigDecimal::add); 

I get the difference between each credit debit pair and add them together with reduce .

+2
source

Source: https://habr.com/ru/post/1264556/


All Articles