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) { }
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)
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With