-2

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...).

Naman
  • 27,789
  • 26
  • 218
  • 353
Caner
  • 57,267
  • 35
  • 174
  • 180

1 Answers1

2
list.stream().map(foo -> foo.field).reduce(BigDecimal.ZERO, (a, b) -> a.add(b));
Caner
  • 57,267
  • 35
  • 174
  • 180
Horatiu Jeflea
  • 7,256
  • 6
  • 38
  • 67