addmeaning addmeaning - 1 year ago 54
Java Question

Sum each field in stream of objects

I want to create instance of object MyObject, each field of which will be sum of values of that field from

I create an object

public class MyObject{
int value;
double length;
float temperature;

MyObject(int value, double length, float temperature){
this.value = value;
this.length = length
this.temperature = temperature

Then I construct list of objects:

List<MyObject> list = new ArrayList<MyObject>{{
add(new MyObject(1, 1d, 1.0f));
add(new MyObject(2, 2d, 2.0f));
add(new MyObject(3, 3d, 3.0f));

I want create object (
new MyObject(6, 6d, 6f)

It is easy to sum one field per stream:

Integer totalValue = myObjects.parallelStream().mapToInt(myObject -> myObject.getValue()).sum(); //returns 6;


Double totalLength = myObjects.parallelStream().mapToDouble(MyObject::getLength).sum(); //returns 6d

and then construct object
new MyObject(totalValue, totalLength, totalTemperature);

But can I sum all fields in one stream?
I want stream to return

new MyObject(6, 6d, 6.0f)

Answer Source

It is a direct application for reduce method:

Stream.of(new MyObject(1, 1d, 1.0f), new MyObject(2, 2d, 2.0f), new MyObject(3, 3d, 3.0f)).
                reduce((a, b) -> new MyObject(a.value + b.value, a.length + b.length, a.temperature + b.temperature))