Calling object methods within Arrays.reduce(…)

  • A+

I have the following 3 files,

class A {      private float b;          public A(float b) {         this.b = b;     }      public float getB() {         return b;     }  }

import java.util.Arrays;  class C {      private A[] d;     private int i = 0;      public C() {         d = new A[2];     }      public float totalB() {         return, f) -> e.getB() + f.getB()).get();     }      public void addB(A b) {         d[i++] = b;     }  }

class D {      public static void main(String[] args) {         C c = new C();         c.addB(new A(3));         c.addB(new A(5));         System.out.println(c.totalB())     }  } 

I was expecting the last line in to output 8, however I get this error:

error: incompatible types: bad return type in lambda expression return, f) -> e.getB() + f.getB()).get(); ^ float cannot be converted to A Why does this happen? I don't see where I'm converting the floats to the object A.


The single argument reduce() variant expects the final result of the reduce operation to be of the same type as the Stream elements.

You need a different variant:

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

which you can use as follows:

public float totalB() {     return,(r, f) -> r + f.getB(), Float::sum); } 


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