new*_*bie 15 java oop object java-8
我有以下3个文件,
A.java:
class A {
private float b;
public A(float b) {
this.b = b;
}
public float getB() {
return b;
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
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())
}
}
Run Code Online (Sandbox Code Playgroud)
我期待D.java中的最后一行输出8,但是我得到了这个错误:
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
为什么会这样?我没有看到我将浮子转换为对象A.
Ous*_* D. 13
我更喜欢使用"sum"方法,因为它比一般reduce模式更具可读性.即
return (float)Arrays.stream(d)
.mapToDouble(A::getB)
.sum();
Run Code Online (Sandbox Code Playgroud)
与您的方法相反,这是更惯用,可读和有效的方法Arrays.stream(d).reduce(...).
Era*_*ran 11
单个参数reduce()变体期望reduce操作的最终结果与Stream元素的类型相同.
您需要一个不同的变体:
<U> U reduce(U identity,
BiFunction<U, ? super T, U> accumulator,
BinaryOperator<U> combiner);
Run Code Online (Sandbox Code Playgroud)
您可以使用如下:
public float totalB() {
return Arrays.stream(d).reduce(0.0f,(r, f) -> r + f.getB(), Float::sum);
}
Run Code Online (Sandbox Code Playgroud)