代码之家  ›  专栏  ›  技术社区  ›  testC0der

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

  •  -1
  • testC0der  · 技术社区  · 2 年前
    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());
    

    但同样的问题。。。

    1 回复  |  直到 2 年前
        1
  •  3
  •   Diego Borba    2 年前

    您正在使用 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