代码之家  ›  专栏  ›  技术社区  ›  newbie

在数组中调用对象方法。reduce(…)

  •  15
  • newbie  · 技术社区  · 7 年前

    我有以下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;
        }
    
    }
    

    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

    3 回复  |  直到 7 年前
        1
  •  11
  •   Eran    7 年前

    reduce() variant期望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
  •  13
  •   Ousmane D.    7 年前

    我更喜欢使用“求和”方法,因为它比一般方法更具可读性 reduce 图案即

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

    这是一种更惯用、可读性更强、效率更高的方法,而不是您的方法 Arrays.stream(d).reduce(...)

        3
  •  3
  •   A_C    7 年前

    正如我在上面的评论中提到的,发布另一个替代方法,您不需要第二个版本的reduce方法。

    public float totalB() {
        return Arrays.stream(d).map(i -> i.getB()).reduce(Float::sum).get();
    }