Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a list with N objects?

Tags:

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) {  } 
like image 669
Marci-man Avatar asked Jul 24 '17 08:07

Marci-man


2 Answers

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) 
like image 96
Eugene Avatar answered Sep 20 '22 05:09

Eugene


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))); 
like image 45
errantlinguist Avatar answered Sep 19 '22 05:09

errantlinguist