java减少int[]数组时出现“错误:找不到适合reduce的方法”

agxfikkp  于 2021-07-14  发布在  Java
关注(0)|答案(1)|浏览(340)

考虑到实现求和的尝试:

int[] nums = { 1,3,4,5,7};
var sum = Arrays.asList(nums).stream().reduce(0,(a,b)->a+b);

像下面这样的问题通常是由于没有足够的类型信息提供给编译器进行类型推断。但是这里我们有一个不含糊的int[]数组作为源。为什么会发生这种错误?

Line 3: error: no suitable method found for reduce(int,(a,b)->a + b)
        var sum = Arrays.asList(nums).stream().reduce(0,(a,b)->a+b);
                                              ^
    method Stream.reduce(int[],BinaryOperator<int[]>) is not applicable
      (argument mismatch; int cannot be converted to int[])
    method Stream.<U>reduce(U,BiFunction<U,? super int[],U>,BinaryOperator<U>) is not applicable
      (cannot infer type-variable(s) U
        (actual and formal argument lists differ in length))
  where U,T are type-variables:
    U extends Object declared in method <U>reduce(U,BiFunction<U,? super T,U>,BinaryOperator<U>)
    T extends Object declared in interface Stream
uqdfh47h

uqdfh47h1#

var sum=arrays.aslist(nums)返回一个列表<int[]>,因此reduce方法将int[]添加到int[],这是不允许的,并且会导致编译错误。
这是一个可能的解决方案:

int[] nums = { 1,3,4,5,7};
    var sum= Arrays.stream(nums).reduce(0,(a,b)->a + b);

var result = Arrays.stream(nums).sum();

相关问题