Search code examples
loopsjava-8java-stream

Using a stream to iterate n times instead of using a for loop to create n items


Say I want to create n items. Pre Java 8, I would write:

List<MyClass> list = new ArrayList<>();
for (int i = 0; i < n; i++) {
    list.add(new MyClass());
}

Is there an elegant way to use a stream to create n items?
I thought of this:

List<MyClass> list = Stream.iterate(0, i -> i).limit(10)
    .map(o -> new MyClass()).collect(Collectors.toList());

Is there a standard/better way of coding this?

Note that the actual usage is a bit more complex and using a stream would be more flexible because I can immediately pump the items through other functions in one line without even creating a reference to the list, for example grouping them:

Stream.iterate(0, i -> i).limit(10).map(o -> new MyClass())
    .collect(Collectors.groupingBy(...));

Solution

  • You could use Stream#generate with limit:

    Stream.generate(MyClass::new).limit(10);