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.