Marci-man
Marci-man

Reputation: 2233

How can I create a list with N objects?

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)
{

}

Upvotes: 41

Views: 33029

Answers (5)

Donald Raab
Donald Raab

Reputation: 6706

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.

Upvotes: 3

errantlinguist
errantlinguist

Reputation: 3828

You could use Stream.generate(Supplier<T>) in combination with a reference to a constructor and then use Stream.limit(long) to specify how many you should construct:

Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toList());    

At least to me, this is more readable and illustrates intent much more clearly than using an IntStream for iteration does as e.g. Alberto Trindade Tavares suggested.

If you want something which performs better in terms of complexity and memory usage, pass the result size to Stream.collect(Collector<? super T,A,R>):

Stream.generate(Objects::new).limit(numOfElements).collect(Collectors.toCollection(() -> new ArrayList<>(numOfElements)));

Upvotes: 48

Alberto Trindade Tavares
Alberto Trindade Tavares

Reputation: 10396

An equivalent implementation of the C# code you mentioned in Java 8, with streams, is the following (EDIT to use mapToObj, suggested by @Eugene):

List <Objects> getList(int numOfElements)
{
  return IntStream.range(0, numOfElements)
                  .mapToObj(x -> new Objects())
                  .collect(Collectors.toList()); 
}

Upvotes: 7

Nico
Nico

Reputation: 1803

Why not keep it simple?? If you want to use LINQ or a Lambda it definetly is possible but the question is if it is more readable or maintainable.

List <Objects> getList(int numOfElements)
{
  List<Objects> objectList = new LinkedList<>();
  for(int i = 0; i <= numOfElements; i++)
  {
    objectList.add(new Object());
  }
  return objectList;
}

If you insist this can be the lambda:

  return IntStream.range(0, numOfElements)
                  .mapToObj(x -> new Objects())
                  .collect(Collectors.toList()); 

Creds to @Alberto Trindade since he posted it faster than me.

Upvotes: 3

Eugene
Eugene

Reputation: 120998

If I got your question right:

List <Object> getList(int numOfElements){
     return IntStream.range(0, numOfElements)
              .mapToObj(Object::new) // or x -> new Object(x).. or any other constructor 
              .collect(Collectors.toList()); 
}

If you want the same object n times:

Collections.nCopies(n, T)

Upvotes: 63

Related Questions