Java8: sum values from specific field of the objects in a list

mat_boy picture mat_boy · Apr 16, 2014 · Viewed 95.2k times · Source

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 in Java8 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)?

Answer

Aniket Thakur picture Aniket Thakur · Apr 16, 2014

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();