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:JavaStreamAPIsrcMain.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:JavaStreamAPIsrcMain.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.
Advertisement
Answer
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().