函数式编程Java 8添加元素的方法
有没有一种更简洁、或许是一行的方式来写以下内容:
ArrayList<Integer> myList = new ArrayList<>();
for (int i = 0; i < 100; i++){
myList.add(i);
}
使用Java8特性和功能上的InPred方法。我并不期待哈斯克尔的解决方案,比如:
ls = [1..100]
但是比传统的命令式风格更优雅
你可以在下面搜索框中键入要查询的问题!
有没有一种更简洁、或许是一行的方式来写以下内容:
ArrayList<Integer> myList = new ArrayList<>();
for (int i = 0; i < 100; i++){
myList.add(i);
}
使用Java8特性和功能上的InPred方法。我并不期待哈斯克尔的解决方案,比如:
ls = [1..100]
但是比传统的命令式风格更优雅
# 1 楼答案
一个解决办法是
步骤如下:
IntStream.range(0, 100)
是100个原始int
的流boxed()
将其转换为Integer
对象流。这是将数字放入Collection
中所必需的李>collect(Collectors.toCollection(ArrayList::new));
是将Stream
转换为ArrayList
的方式。对于集合,您可以用任何供应商替换ArrayList::new
,元素将被添加到该集合中李>