Home > Enterprise >  Stream API reduce method not working while adding elements
Stream API reduce method not working while adding elements

Time:03-25

I am trying to add elements of int array using Stream API.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5};
        int sum = Arrays.asList(a).stream().reduce(0, (psum, x) -> psum x);
        System.out.println(sum);
    }
}

But its is giving this error message.

E:\Java\StreamAPI\src\Main.java:6:44
java: no suitable method found for reduce(int,(psum,x)->psum   x)
    method java.util.stream.Stream.reduce(int[],java.util.function.BinaryOperator<int[]>) is not applicable
      (argument mismatch; int cannot be converted to int[])
    method java.util.stream.Stream.<U>reduce(U,java.util.function.BiFunction<U,? super int[],U>,java.util.function.BinaryOperator<U>) is not applicable
      (cannot infer type-variable(s) U
        (actual and formal argument lists differ in length))

I even tried doing this

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5};
        int sum = Arrays.asList(a).stream().reduce(0, Integer::sum);
        System.out.println(sum);
    }
}

I got this error message:

E:\Java\StreamAPI\src\Main.java:6:44
java: no suitable method found for reduce(int,Integer::sum)
    method java.util.stream.Stream.reduce(int[],java.util.function.BinaryOperator<int[]>) is not applicable
      (argument mismatch; int cannot be converted to int[])
    method java.util.stream.Stream.<U>reduce(U,java.util.function.BiFunction<U,? super int[],U>,java.util.function.BinaryOperator<U>) is not applicable
      (cannot infer type-variable(s) U
        (actual and formal argument lists differ in length))

Both of these examples were given in this Baeldung article about reduce in stream api.

CodePudding user response:

Your issue is that Arrays.asList(int[]) doesn't do what you think it does. It creates a list with a single element, an integer array. It does not create a list containing several integers. (And note that the Baeldung article you link doesn't use Array.asList on an int[], either.)

Instead, write Arrays.stream(a).reduce(0, Integer::sum), or even Arrays.stream(a).sum().

CodePudding user response:

The problem you are facing is, that you input a int[] into the Arrays.ofList-method.

The return type of the call Arrays.ofList(int[]) would be List<int[]>, which is currently not supported. Thus it is being interpreted you wanting a list with only a single element of type int[].

To circumvent that, you can either declare the list using the boxed types (Integer, Double, etc.) or use different Methods to generate a stream of integers.

Solution 1: Use Boxed Types

Integer[] a = {1,2,3,4,5};
int sum = Arrays.asList(a).stream().reduce(0, (psum, x) -> psum x);
System.out.println(sum);
// prints 15

Solution 2: Use Arrays.asList with varargs directly

int sum = Arrays.asList(1,2,3,4,5).stream().reduce(0, (psum, x) -> psum x);
System.out.println(sum);
// prints 15

Solution 3: Use Stream with varargs directly

Similar to the previous solution but generating directly the stream without an intermediate list.

int sum = Stream.of(1,2,3,4,5).reduce(0, (psum, x) -> psum x);
System.out.println(sum);
// prints 15

Solution 4: Use IntStream with varargs directly

Java offers multiple different types of Stream one of them being IntStream. This offers an unboxed version for primitives.

int sum = IntStream.of(1,2,3,4,5).reduce(0, (psum, x) -> psum x);
System.out.println(sum);
// prints 15

Bonus

An alternative to using reduce(0, (psum, x) -> psum x) would be using some adding-operation.

You could use Integer.sum(int a, int b) which fulfills the contract of reduce.

int sum = IntStream.of(1,2,3,4,5).reduce(0, Integer::sum);
System.out.println(sum);
// prints 15

Using an IntStream offers an additional benefit having the method sum().

int sum = IntStream.of(1,2,3,4,5).sum();
System.out.println(sum);
// prints 15

In case you are not able to generate an IntStream yourself and need to work with a Stream<Integer>, you can also map to an IntStream.

int sum = Stream.of(1,2,3,4,5).mapToInt(Integer::intValue).sum()
System.out.println(sum);
// prints 15
  •  Tags:  
  • java
  • Related