Parallel streams
We have seen that changing from a sequential stream to a parallel stream can lead to incorrect results if code was not written and tested to process a parallel stream. The following are a few more considerations related to parallel streams.
Stateless and stateful operations
There are stateless operations, such as filter()
, map()
, and flatMap()
, which do not keep data around (do not maintain state) while moving processing from one stream element to the next. Also, there are stateful operations, such as distinct()
, limit()
, sorted()
, reduce()
, and collect()
, that can pass a state from previously processed elements to the processing of the next element.
Stateless operations usually do not pose a problem while switching from a sequential stream to a parallel one. Each element is processed independently, and the stream can be broken into any number of substreams for independent processing. With stateful operations, the situation is different. To start with, using...