有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

函数式编程Java 8添加元素的方法

有没有一种更简洁、或许是一行的方式来写以下内容:

ArrayList<Integer> myList = new ArrayList<>();
for (int i = 0; i < 100; i++){
    myList.add(i);
}

使用Java8特性和功能上的InPred方法。我并不期待哈斯克尔的解决方案,比如:

ls = [1..100]

但是比传统的命令式风格更优雅


共 (1) 个答案

  1. # 1 楼答案

    一个解决办法是

    List<Integer> list = IntStream.range(0, 100).boxed().collect(Collectors.toCollection(ArrayList::new));
    

    步骤如下:

    1. IntStream.range(0, 100)是100个原始int的流
    2. boxed()将其转换为Integer对象流。这是将数字放入Collection中所必需的
    3. collect(Collectors.toCollection(ArrayList::new));是将Stream转换为ArrayList的方式。对于集合,您可以用任何供应商替换ArrayList::new,元素将被添加到该集合中