Calling object methods within Arrays.reduce(...)

newbie :

I have the following 3 files,

A.java:

class A {

    private float b;    

    public A(float b) {
        this.b = b;
    }

    public float getB() {
        return b;
    }

}

C.java:

import java.util.Arrays;

class C {

    private A[] d;
    private int i = 0;

    public C() {
        d = new A[2];
    }

    public float totalB() {
        return Arrays.stream(d).reduce((e, f) -> e.getB() + f.getB()).get();
    }

    public void addB(A b) {
        d[i++] = b;
    }

}

D.java:

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 D.java to output 8, however I get this error:

error: incompatible types: bad return type in lambda expression return Arrays.stream(d).reduce((e, 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.

Eran :

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 Arrays.stream(d).reduce(0.0f,(r, f) -> r + f.getB(), Float::sum);
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=35735&siteId=1