Understanding parallel streams
All of the streams so far have been serial streams where the results are ordered. With serial streams, a single thread processes one entry at a time. A parallel stream is processed by multiple threads executing concurrently (running on multiple CPUs). The stream elements are split into substreams, which are processed by multiple instances of the stream pipeline being executed in multiple threads. These partial substream results are then combined into a final result. To execute the substreams in parallel, the streams use the support of Java’s fork/join framework for thread management.
Creating parallel streams
To make a stream a parallel stream is very straightforward. We have two options: we can use the parallelStream()
method from the Collection
API or the parallel()
intermediate operation from the Stream
API.
Here are examples of both methods:
Stream<String> parallelFarmAnimals = List.of("sheep"...