Home » Java » java – Sum a list of objects based on BigDecimal field in single line-Exceptionshub

java – Sum a list of objects based on BigDecimal field in single line-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

Suppose we have:

class Foo {
   public BigDecimal field;
}

and that we have a list of Foo instances, i.e. List<Foo> list.

How can we calculate the sum of the values of the field from the objects in the list in a single line?

I found examples of similar cases using streams but they handle simpler cases and do not work for this; such as calculating for List<Integer> or when the field is something easily “summable” (int, Integer…).

How to&Answers:
list.stream().map(foo -> foo.field).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));