Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum BigDecimal properties of objects in Java8 lambda expression?

Tags:

java

java-8

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?

like image 926
Mateus Viccari Avatar asked Jan 20 '15 17:01

Mateus Viccari


People also ask

How do you sum BigDecimal values?

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.

How do I add three BigDecimal values in Java?

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.


1 Answers

invoiceItems.stream()
    .map(Item::getItemValue)
    .reduce(BigDecimal.ZERO, BigDecimal::add)
like image 110
Louis Wasserman Avatar answered Oct 11 '22 04:10

Louis Wasserman