Search code examples
javastreamreduce

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


Given this attempt to implement a sum :

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

Problems like the following are typically due to insufficient type information provided to the compiler for type inference. But here we have a non-ambiguous int[] array as the source. Why is this error then happening?

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


Solution

  • var sum = Arrays.asList(nums) returns a List<int[]> and consequently the reduce method adds int[] to int[], this is not allowed and leads to compilation error.

    This is a possible solution:

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

    or

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