Why is list.parallelStream().forEach() not processing all the elements in the list in Java?
Because ArrayList
is not a thread-safe collection. Using a thread-safe collection like CopyOnWriteArrayList
would make it correct but not necessarily efficient.
Using a Collector
instead would be much simpler and correct. e.g.
source.parallelStream().collect(Collectors.toList())
The forEach
operation of the parallel stream is adding elements to an un-synchronized Collection
(an ArrayList
) from multiple threads. Therefore, the operation is not thread safe, and has unexpected results.
Using forEachOrdered()
instead of forEach()
will ensure all the elements of the source
List
are added to the destination
List
.
However, as mentioned in the other answer, using collect(Collectors.toList())
is the correct way to produce an output List
from a Stream
.