Lets say I have a Class Obj.
public class Obj {
private double prop1;
private double prop2;
private double prop3;
private double prop4;
// assume getters, setters and constructors are created
}
And a List with multiple instances in it (in this example only two).
List<Obj> objList = List.of(new Obj(12.9, 3.4, 38.6, 0.3), new Obj(0.123, 95.4, 23.0, 7.56));
What would be the most efficient way to end up with an object that has the sum of the values of the same properties from all the instances in the List?
Obj{13.023, 98.8, 61.6, 7.86}
We can use java 8 reduce to accomplish this fairly trivially.
List<Obj> objList = List.of(new Obj(12.9, 3.4, 38.6, 0.3), new Obj(0.123, 95.4, 23.0, 7.56));
Obj total = objList.stream().reduce(new Obj(), (subtotal, element) -> {
subtotal.setProp1(subtotal.getProp1() + element.getProp1());
subtotal.setProp2(subtotal.getProp2() + element.getProp2());
subtotal.setProp3(subtotal.getProp3() + element.getProp3());
subtotal.setProp4(subtotal.getProp4() + element.getProp4());
return subtotal;
});
This makes use of passing reduce a new Object that has initial values of 0 for all of your doubles, then we use an accumulator to update the value, reducing it to 1 value.