Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 703
mat_boy Avatar asked Apr 16 '14 13:04

mat_boy


People also ask

How do you sum an object in Java?

Using Stream.collect() asList(1, 2, 3, 4, 5); Integer sum = integers. stream() . collect(Collectors. summingInt(Integer::intValue));

How do I get a list of fields from a list of objects?

The list of all declared fields can be obtained using the java. lang. Class. getDeclaredFields() method as it returns an array of field objects.

How do you sum a list in Java?

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.


2 Answers

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(); 
like image 126
Aniket Thakur Avatar answered Oct 13 '22 04:10

Aniket Thakur


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)); 
like image 20
Sotirios Delimanolis Avatar answered Oct 13 '22 03:10

Sotirios Delimanolis