mat_boy
mat_boy

Reputation: 13666

Sum values from specific field of the objects in a list

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

Upvotes: 115

Views: 193697

Answers (6)

Muruganandam C
Muruganandam C

Reputation: 97

You can do this method: "IntSummaryStatistics"

IntSummaryStatistics insum = lst.stream().filter(v-> v%2==0).mapToInt(mapper->mapper).summaryStatistics();
int sum = insum.getSum();

Upvotes: 1

Zon
Zon

Reputation: 19880

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

List<Obj> objs ...

Double sum = objs.stream()
  .filter(Objects::notNull);
  .mapToDouble(Obj::getField)
  .sum();

Upvotes: 7

Aniket Thakur
Aniket Thakur

Reputation: 68915

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

Upvotes: 213

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

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

Upvotes: 14

JeanValjean
JeanValjean

Reputation: 17713

Try:

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

Upvotes: 6

Paweł Ćwik
Paweł Ćwik

Reputation: 161

You can try

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

Like explained here

Upvotes: 9

Related Questions