Home > Mobile >  How to sum values of the same properties from multiple objects into a new object in Java
How to sum values of the same properties from multiple objects into a new object in Java

Time:03-16

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

How could I 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}

CodePudding user response:

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.

CodePudding user response:

I'd create a no-arg constructor and a merge() method

public Obj merge(Obj o) {
    if (o != null) {
        this.prop1  = o.prop1;
        //etc etc
    }
    return this;
}

then to get the summation:

Obj sum = new Obj();
for (Obj o : list) {
   sum.merge(o);
}
  • Related