[英]Java 8 - Initialising List (List)
I have a question concerning Java 8 and Lists. 我有一个关于Java 8和列表的问题。 Is it possible to initialise a List easier than my code below is?
是否有可能比我下面的代码更容易初始化列表?
final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
weekScheduler.add(0, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(1, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(2, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(3, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(4, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(5, new ArrayList<ScheduleIntervalContainer>());
weekScheduler.add(6, new ArrayList<ScheduleIntervalContainer>());
Personally I would just use a for
loop: 我个人只是使用
for
循环:
List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
for (int i = 0; i < 7; i++)
weekScheduler.add(new ArrayList<>());
However, if you want a Java 8 solution: 但是,如果要使用Java 8解决方案:
List<List<ScheduleIntervalContainer>> weekScheduler
= Stream.generate(ArrayList<ScheduleIntervalContainer>::new)
.limit(7)
.collect(Collectors.toList());
You can use: 您可以使用:
List<List<ScheduleIntervalContainer>> weekScheduler =
IntStream.rangeClosed(0, 6).mapToObj(i -> new ArrayList<ScheduleIntervalContainer>())
.collect(Collectors.toList());
This will create a Stream of int
values going from 0 to 6 (included), map each of those ints to a new ArrayList
of your class and collect the result to a List
. 这将创建一个从0到6(包括)的
int
值流,将每个int映射到您的类的新ArrayList
并将结果收集到List
。
You can use a loop or an IntStream. 您可以使用循环或IntStream。
final List<List<ScheduleIntervalContainer>> weekScheduler = new ArrayList<>();
IntStream.range(0, 7).forEach(day -> weekScheduler.add(new ArrayList<>()));
Whenever I code with lists, I use a for loop to speed up the declaration. 每当我用列表编码时,我都会使用for循环来加快声明速度。 In your case, I would heavily suggest a loop of any kind, but a for loop would probably be the easiest.
在您的情况下,我会大量建议任何一种循环,但是for循环可能是最简单的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.