Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - fill ArrayList

Is there a better way to fill an ArrayList like this (I have done it like this in Java 7):

List<ScheduleIntervalContainer> scheduleIntervalContainers = new ArrayList<>();
scheduleIntervalContainers.add(scheduleIntervalContainer);
like image 698
quma Avatar asked Oct 15 '15 05:10

quma


1 Answers

To fill a List, it is possible to generate an infinite Stream using Stream.generate(s) and then limit the number of results with limit(maxSize).

For example, to fill a List of 10 new ScheduleIntervalContainer objects:

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

The generate method takes a Supplier: in this case, the supplier is a method reference creating new instance of ScheduleIntervalContainer each time.

like image 180
Tunaki Avatar answered Oct 28 '22 01:10

Tunaki