Suppose to have a class Obj
:
class Obj { int field; }
...and that you have a list of Obj
instances, i.e. List<Obj> lst
.
Now, how can I find with streams the sum of the values of the int fields field
from the objects in list lst
under a filtering criterion (e.g. for an object o
, the criterion is o.field > 10
)?
Using Stream.collect() asList(1, 2, 3, 4, 5); Integer sum = integers. stream() . collect(Collectors. summingInt(Integer::intValue));
The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.
A simple solution to calculate the sum of all elements in a List is to convert it into IntStream and call sum() to get the sum of elements in the stream. There are several ways to get IntStream from Stream<Integer> using mapToInt() method.
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();
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));
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