Reduce operation on custom object in java

  • A+
Category:Languages

How to use Reduce operation for performing sum on two fields of an object.

e.g.     class Pojo     {         public Pojo(int a, int b) {             super();             this.a = a;             this.b = b;         }         int a ;         int b;         public int getA() {             return a;         }         public void setA(int a) {             this.a = a;         }         public int getB() {             return b;         }         public void setB(int b) {             this.b = b;         }      }      Pojo object1 = new Pojo(1,1);     Pojo object2 = new Pojo(2,2);     Pojo object3 = new Pojo(3,3);     Pojo object4 = new Pojo(4,4);      List<Pojo> pojoList = new ArrayList<>();      pojoList.add(object1);     pojoList.add(object2);     pojoList.add(object3);     pojoList.add(object4); 

I can perform sum using IntStrem like this

int sum = pojoList.stream()                   .mapToInt(ob ->(ob.getA()+ob.getB()))                   .sum(); 

I want to perform the same operation using reduce, But somehow I am not getting the syntax correct.

pojoList.stream()         .reduce(0,(myObject1,myObject2) ->(myObject1.getA()+ myObject2.getB())); 


Well, if you want to call reduce on the IntStream:

int sum = pojoList.stream()                   .mapToInt(ob ->(ob.getA()+ob.getB()))                   .reduce(0, (a,b)->a+b); 

Of course, the same will work on a Stream<Integer>:

int sum = pojoList.stream()                   .map(ob ->(ob.getA()+ob.getB()))                   .reduce(0, (a,b)->a+b); 

or with a method reference:

int sum = pojoList.stream()                   .map(ob ->(ob.getA()+ob.getB()))                   .reduce(0, Integer::sum); 

or without the map():

int sum = pojoList.stream()                   .reduce(0, (s,ob)->s+ob.getA()+ob.getB(),Integer::sum); 

In this last example, I use the variant:

<U> U reduce(U identity,              BiFunction<U, ? super T, U> accumulator,              BinaryOperator<U> combiner); 

since the reduced value (an Integer) is different than the type of the Stream elements.

The first parameter is an identity value - 0.

The second parameter adds the getA() and getB() values of the current Pojo element to the intermediate sum.

The third parameter combines two partial sums.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: