Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list with specific size of elements

Say, I want to create a list quickly which contains 1000 elements. What is the best way to accomplish this?

like image 1000
user705414 Avatar asked Nov 25 '11 10:11

user705414


1 Answers

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);
like image 104
aioobe Avatar answered Nov 14 '22 21:11

aioobe