Sum values from specific field of the objects in a list

JavaFilterJava 8Java Stream

Java Problem Overview


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

Java Solutions


Solution 1 - Java

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 - Java

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 3 - Java

You can try

int sum = list.stream().filter(o->o.field>10).mapToInt(o->o.field).sum();

Like explained here

Solution 4 - Java

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();

Solution 5 - Java

In Java 8 for an Obj entity with field and getField() method you can use:

List<Obj> objs ...

Stream<Obj> notNullObjs =
  objs.stream().filter(obj -> obj.getValue() != null);

Double sum = notNullObjs.mapToDouble(Obj::getField).sum();

Solution 6 - Java

You can do this method: "IntSummaryStatistics"

IntSummaryStatistics insum = li.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionmat_boyView Question on Stackoverflow
Solution 1 - JavaAniket ThakurView Answer on Stackoverflow
Solution 2 - JavaSotirios DelimanolisView Answer on Stackoverflow
Solution 3 - JavaPaweł ĆwikView Answer on Stackoverflow
Solution 4 - JavaJeanValjeanView Answer on Stackoverflow
Solution 5 - JavaZonView Answer on Stackoverflow
Solution 6 - JavaMuruganandam CView Answer on Stackoverflow