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?
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.
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.
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.
Just reduce it to:
BigDecimal sumCreditDebit = ledgeredEntries.stream().map(p -> p.getCreditAmount()
.subtract(p.getDebitAmount()))
.reduce(BigDecimal.ZERO, BigDecimal::add);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With