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

84 Views Asked by At
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

.collect(Collectors.toList());

but same problem...

1

There are 1 best solutions below

0
Diego Borba On BEST ANSWER

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.