Java 8 stream list collector memory allocation speed vs loop with preallocation
Behind the scenes Collectors.toList()
will allow to collect the resulting elements of your Stream
into an ArrayList
created with the default constructor so with a default capacity of 10
so indeed a reallocation will be required in case the size exceeds 10
.
If you want to use a different List
's implementation, use toCollection(Supplier<C> collectionFactory)
which is a more generic collector allowing to provide the factory of your target Collection
.
For example, if you want to collect the elements into a LinkedList
instead, you could rewrite your code as next:
List<Integer> result = myList.stream()
.map(doWhatever)
.collect(Collectors.toCollection(LinkedList::new));
Assuming that you want an ArrayList
with a default capacity of 100
, the collector would be Collectors.toCollection(() -> new ArrayList<>(100))
.
Collectors.toList()
does not specify anything about its implementation. If you care, use toCollection(ArrayList::new)
.
Should I not use streams with list collectors if I know the size of the resulting list from the beginning on?
Nah, go ahead and use them. Allocation is cheap and the cost is minimal relative to the conciseness win. Presizing lists is generally a premature optimization.