Let's get a simple real life example:
BigDecimal invoiceValue = BigDecimal.ZERO;
for (InvoiceItem i : invoiceItems) {
invoiceValue = invoiceValue.add(i.getItemValue());
}
How to get this in one statement with Java8 lambda expression?
math. BigDecimal. add(BigDecimal val) is used to calculate the Arithmetic sum of two BigDecimals. This method is used to find arithmetic addition of large numbers of range much greater than the range of largest data type double of Java without compromising with the precision of the result.
BigDecimal. add(BigDecimal augend, MathContext mc) returns a BigDecimal whose value is (this + augend), with rounding according to the MathContext settings. If either number is zero and the precision setting is nonzero then the other number, rounded if necessary, is used as the result.
invoiceItems.stream()
.map(Item::getItemValue)
.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