Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Stream API reduce method not working while adding elements

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading