Why forEach
prints numbers in random order, while collect
always collects elements in original order, even from parallel stream?
In
The Collectors.toList method specifies that the returned Collector
adds elements to the list in encounter order.
Returns:
a Collector which collects all the input elements into a List, in encounter order
It doesn't matter whether the Stream
is parallel; the order is preserved.
Additionally, looking at the Collectors
source code, the returned Collector
calls addAll
on an ArrayList
when merging, and that preserves the order. E.g. if one thread has {1, 2} and the next thread has {3, 4}, then the call to addAll
yields {1, 2, 3, 4}. Also, the returned Collector
doesn't have the UNORDERED
characteristic.