JAVA中list.stream()中.collect()方法的问题[重复]

问题描述 投票:0回答:1
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

尝试了所有程序给出的修复,询问chatGPT,但没有结果。我看不出问题所在。

我也尝试过

.collect(Collectors.toList());

但同样的问题...

java arraylist collections java-stream collectors
1个回答
3
投票

您无缘无故地使用

mapToInt()
,您可以这样做:

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

您还可以将

.collect(Collectors.toList())
替换为
.toList()
,该功能自 java 16 起可用。

© www.soinside.com 2019 - 2024. All rights reserved.