鉴于以下列表,我将如何迭代地使用参数FactoryWithArgs
添加0 - 100
类型的元素,同时仍然将此代码保持在(基本上)一行中?
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()));
答案 0 :(得分:2)
由于@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()
的内容,并将它们合并为一个流,然后我们将其转换回List( .collect(Collectors.toList()
);
答案 1 :(得分:0)
final List<Factory> list = new ArrayList<Factory>();
list.add(new Factory0());
list.add(new Factory1());
list.add(new Factory2());
for (int i = 0; i < 101; i++) {
list.add(new FactoryWithArgs(i));
}
list.add(new Factory4());
list.add(new Factory5());
如果您愿意,可以将其放入方法中。