Sum values from specific field of the objects in a list
Solution 1:
You can do
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(o -> o.getField()).sum();
or (using Method reference)
int sum = lst.stream().filter(o -> o.getField() > 10).mapToInt(Obj::getField).sum();
Solution 2:
You can try
int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();
Like explained here
Solution 3:
You can also collect
with an appropriate summing collector like Collectors#summingInt(ToIntFunction)
Returns a
Collector
that produces the sum of a integer-valued function applied to the input elements. If no elements are present, the result is 0.
For example
Stream<Obj> filtered = list.stream().filter(o -> o.field > 10);
int sum = filtered.collect(Collectors.summingInt(o -> o.field));
Solution 4:
Try:
int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();