Java 8 - populate ArrayList

Is there a better way to populate ArrayListlike this (I did it like this in Java 7):

List<ScheduleIntervalContainer> scheduleIntervalContainers = new ArrayList<>();
scheduleIntervalContainers.add(scheduleIntervalContainer);
+4
source share
1 answer

To fill a List, you can create infinite Streamwith Stream.generate(s), and then limit the number of results with limit(maxSize).

For example, to fill Listout 10 new objects ScheduleIntervalContainer:

List<ScheduleIntervalContainer> scheduleIntervalContainers = 
        Stream.generate(ScheduleIntervalContainer::new).limit(10).collect(toList());

The method generateaccepts Supplier: in this case, the provider is a reference to a method that creates a new instance ScheduleIntervalContainereach time.

+10
source

Source: https://habr.com/ru/post/1611711/


All Articles