How to create a list with a specific item size

Let's say I want to quickly create a list containing 1000 items. What is the best way to do this?

+4
source share
2 answers

You can use Collections.nCopies .

Note that the returned list is immutable. In fact, the docs say that "the newly allocated data object is tiny (it contains a single reference to the data object)."

If you need a modified list, you would do something like

 List<String> hellos = new ArrayList<String>(Collections.nCopies(1000, "Hello")); 

If you want 1000 individual objects, you can use

 List<YourObject> objects = Stream.generate(YourObject::new) .limit(1000) .collect(Collectors.toList()); 

Again, there are no guarantees regarding the possibilities of implementing the resulting list. If you need, say ArrayList , you would do

  ... .collect(ArrayList::new); 
+14
source

Fastest: int[] myList = new int[1000] will contain 1000 elements equal to zero. But I am sure that this does not fit your needs. Tell us more about what you need and I could help :)

0
source

Source: https://habr.com/ru/post/1383026/


All Articles