Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streams : Calculate the difference of totals in one go

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

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?

like image 342
Krishan Avatar asked Feb 22 '17 07:02

Krishan


People also ask

How can we get an average of values of elements in a stream operation?

IntStream average() method in Java The average() method of the IntStream class in Java returns an OptionalDouble describing the arithmetic mean of elements of this stream, or an empty optional if this stream is empty. It gets the average of the elements of the stream.

Can a stream be used multiple times?

A Stream should be operated on (invoking an intermediate or terminal stream operation) only once. A Stream implementation may throw IllegalStateException if it detects that the Stream is being reused. Whenever a terminal operation is called on a Stream object, the instance gets consumed and closed.

What is stream reduction?

More specifically, reduction stream operations allow us to produce one single result from a sequence of elements, by repeatedly applying a combining operation to the elements in the sequence. In this tutorial, we'll look at the general-purpose Stream. reduce() operation and see it in some concrete use cases.


1 Answers

Just reduce it to:

BigDecimal sumCreditDebit = ledgeredEntries.stream().map(p -> p.getCreditAmount()
        .subtract(p.getDebitAmount()))
        .reduce(BigDecimal.ZERO, BigDecimal::add);
like image 191
M A Avatar answered Sep 24 '22 01:09

M A