7

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);
Tunaki
  • 132,869
  • 46
  • 340
  • 423
quma
  • 5,233
  • 26
  • 80
  • 146
  • 1
    What's wrong with that way? – Eran Oct 15 '15 at 05:28
  • I'm not aware of a way, but Java 8 features are not something I have a lot of expertise in. But when I look at your code, the only thing that makes it look long and cumbersome are long variable names. Personally I wouldn't shorten those either because I'd rather long descriptive names and self documenting code over brevity and so will anyone who has to maintain the code. – Sammy Oct 15 '15 at 05:40
  • 2
    `List scheduleIntervalContainers = new ArrayList<>(Arrays.asList(scheduleIntervalContainer));` – Alexis C. Oct 15 '15 at 08:45
  • 2
    @Alexis C.: for a single element list, there is `Collections.singletonList(…))` which spares you from creating an array… – Holger Oct 15 '15 at 09:22
  • 3
    It’s not clear what you are asking. You talk about “filling” but are actually only adding a single element. What better way to add a single element to a list than invoking a method named `add` on that list can you imagine? – Holger Oct 15 '15 at 09:24

1 Answers1

14

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.

Tunaki
  • 132,869
  • 46
  • 340
  • 423