在Arrays.reduce(...)中调用对象方法

时间:2018-11-15 14:00:24

标签: 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;
    }

}

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())
    }

}

我期望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的位置。

3 个答案:

答案 0 :(得分:13)

我更喜欢使用“ sum”方法,因为它比一般的reduce模式更具可读性。即

return (float)Arrays.stream(d)
                    .mapToDouble(A::getB)
                    .sum();

与您使用Arrays.stream(d).reduce(...) ...

的方法相比,这是一种更加惯用,可读和有效的方法。

答案 1 :(得分:11)

单个参数reduce()的变体期望reduce操作的最终结果与Stream元素的类型相同。

您需要一个different variant

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

您可以按如下方式使用:

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

答案 2 :(得分:3)

如我在上面的评论中所述,在不需要第二版的reduce方法的地方发布另一种选择。

Dim shP As Object
Dim myShape As Object
Dim mySlide As Object
Dim tempSize As Integer, tempFont As String

Worksheets("Sheet 1").Activate

'select the name of report
Set shP = Range(V.Title)

'select the ppt sheet you wish to copy the object to
Set mySlide = PPT.ActivePresentation.slides(1)

'count the number of shapes currently on the PPT
shapeCount = mySlide.Shapes.Count
'copy the previously selected shape
shP.Copy
'paste it on the PPT
mySlide.Shapes.Paste

'wait until the count of shapes on the PPT increases, which signals that the past operation is finished.
Do '<~~ wait completion of paste operation
    DoEvents
Loop Until mySlide.Shapes.Count > shapeCount

'adjust formatting of the newly copied shape: position on the sheet, font & size
Set myShape = mySlide.Shapes(mySlide.Shapes.Count)

    myShape.Left = 254.016
    myShape.Top = 42.8085
    myShape.Width = 286.0515
    myShape.Height = 46.7775
    myShape.TextEffect.FontSize = 15
    myShape.TextEffect.FontName = "Century Schoolbook"