user705414
user705414

Reputation: 21200

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?

Upvotes: 7

Views: 9142

Answers (2)

aioobe
aioobe

Reputation: 421040

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

Upvotes: 20

solendil
solendil

Reputation: 8458

Fastest : int[] myList = new int[1000] will contain 1000 elements equal to zero. But I'm sure it doesn't suit your needs. Tell us more of what you need and I might be able to help :)

Upvotes: 0

Related Questions