Say, I want to create a list quickly which contains 1000 elements. What is the best way to accomplish this?
You can use Collections.nCopies.
Note however that the list returned is immutable. In fact, the docs says "it the newly allocated data object is tiny (it contains a single reference to the data object)".
If you need a mutable list, you would do something like
List<String> hellos = new ArrayList<String>(Collections.nCopies(1000, "Hello"));
If you want 1000 distinct objects, you can use
List<YourObject> objects = Stream.generate(YourObject::new)
.limit(1000)
.collect(Collectors.toList());
Again, there is not guarantees about the capabilities of the resulting list implementation. If you need, say an ArrayList, you would do
...
.collect(ArrayList::new);
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