"Error: no suitable method found for reduce" when reducing an int[] array

"Error: no suitable method found for reduce" when reducing an int[] array

鉴于此尝试实现总和:

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

var sum = Arrays.asList(nums) returns a List 因此 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();