gpt4 book ai didi

Java迭代添加Arrays.asList中的所有内容

转载 作者:行者123 更新时间:2023-11-30 03:18:59 25 4
gpt4 key购买 nike

给定以下列表,我将如何迭代添加带有参数 0 - 100FactoryWithArgs 类型的元素,同时仍将此代码(本质上)保留在一行中?

final List<Factory> list = new ArrayList<Factory>(Arrays.asList(
new Factory0(), new Factory1(), new Factory2(),
new FactoryWithArgs(0), new FactoryWithArgs(1), ... ,
new FactoryWithArgs(99), new FactoryWithArgs(100),
new Factory4(), new Factory5()));

最佳答案

由于 @Brian 对“双括号”初始化的评论是不可以的,这里有另一个建议。

对于FactoryWithArgs类我会做一个 FactoryWithArgsMaker旨在制作 FactoryWithArgs 的类对象作为 List .

类似于:

public static class FactoryWithArgsMaker {
public static List<FactoryWithArgs> makeNew(int start, int end) {
List<FactoryWithArgs> list = new ArrayList();
for (int i = 0; i <= end; i++) {
list.add(new FactoryWithArgs(i));
}
return list;
}
}

只要“工厂”的顺序在列表中并不重要,并且使用 Java 8 Stream您可以像这样在一行中初始化您的列表:

List<Factory> list = Stream.concat(
Arrays.asList(
new Factory0(), new Factory1(), new Factory2(),
new Factory3(), new Factory4(), new Factory5()
).stream(),
FactoryWithArgsMaker.makeNew(0, 100).stream()
).collect(Collectors.toList());

Stream.concat()Arrays.asList() 的内容和 List<FactoryWithArgs> ,从 FactoryWithArgsMaker.makeNew() 返回,并将它们组合成一个流,然后将其转换回列表 ( .collect(Collectors.toList() );

关于Java迭代添加Arrays.asList中的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31814815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com