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

Problem with .collect() method in list .stream() in JAVA

public class PositiveNumbers {
    public static List<Integer> positive(List<Integer> numbers){

        return numbers.stream()
                .mapToInt(Integer::valueOf)
                .filter(s -> s >= 0)
                .collect(Collectors.toCollection(ArrayList<Integer>::new));
    }
}


Image of the code and description of problem given by IntelliJ

Tried all that program gives as fix, asked chatGPT, but no results. I cannot see the problem.

I tried also

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

.collect(Collectors.toList());

but same problem…

>Solution :

You are using mapToInt() without any reason, you can do this way:

public static List<Integer> positive(List<Integer> numbers) {
    return numbers.stream()
                  .filter(s -> s >= 0)
                  .collect(Collectors.toList());
}

You can also, replace .collect(Collectors.toList()) with .toList(), which is available since java 16.

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