Mar*_*man 11 java collections list java-8
我正在尝试创建一个包含n个元素的对象列表.我试图以尽可能多的java 8方式做到这一点.类似于c#的问题: 创建N个对象并将它们添加到列表中
像这样的东西:
List <Objects> getList(int numOfElements)
{
}
Run Code Online (Sandbox Code Playgroud)
err*_*ist 23
您可以Stream.generate(Supplier<T>)结合使用对构造函数的引用,然后使用它Stream.limit(long)来指定应该构造的数量:
Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
至少对我而言,这比使用IntStream迭代更加清晰,更清楚地说明了意图,例如Alberto Trindade Tavares所建议的.
如果您想要在复杂性和内存使用方面表现更好的东西,请将结果大小传递给Stream.collect(Collector<? super T,A,R>):
Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toCollection(() -> new ArrayList<>(numOfElements)));
Run Code Online (Sandbox Code Playgroud)
Eug*_*ene 21
如果我的问题是正确的:
List <Object> getList(int numOfElements){
return IntStream.range(0, numOfElements)
.mapToObj(Object::new) // or x -> new Object(x).. or any other constructor
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)
如果你想要同一个对象n次:
Collections.nCopies(n, T)
Run Code Online (Sandbox Code Playgroud)
您在 Java 8 中提到的 C# 代码的等效实现streams如下(编辑以使用 mapToObj,由 @Eugene 建议):
List <Objects> getList(int numOfElements)
{
return IntStream.range(0, numOfElements)
.mapToObj(x -> new Objects())
.collect(Collectors.toList());
}
Run Code Online (Sandbox Code Playgroud)