How can I create a list with N objects?

Viewed 20965

I am trying to create a list of objects with n elements. I am trying to do this in the most java 8 way as possible. Something similar to the question asked for c# here : Creating N objects and adding them to a list

Something like this:

List <Objects> getList(int numOfElements)
{

}
5 Answers

If you don't mind a third-party dependency, the following will work with Eclipse Collections:

List<Object> objects = Lists.mutable.withNValues(10, Object::new);
Verify.assertSize(10, objects);

Note: I am a committer for Eclipse Collections.

Related