Streams
Parallel Streams
Copyright © Seán Kennedy
Parallel Streams
• All of the streams thus far have been sequential streams i.e.
the streams have processed the data one element at a time.
• Parallel streams can process elements in a stream
concurrently i.e. at the same time.
• Java achieves this by splitting the stream up into sub-
streams and then the pipeline operations are performed on
the sub-streams concurrently (each sub-stream has its own
thread).
Copyright © Seán Kennedy
Parallel Streams
• To make a stream parallel, we can use the parallel() or
parallelStream() methods.
• parallel() is available in Stream<T>.
• parallelStream() is defined in the Collection<E> interface
Copyright © Seán Kennedy
Parallel Streams
Collection<E>
Stream<T>
Copyright © Seán Kennedy
Parallel Streams
• Firstly, let’s look at a sequential stream that sums up a
stream of numbers.
Sequential stream
Copyright © Seán Kennedy
Parallel Streams
Parallel stream
Copyright © Seán Kennedy
Parallel Streams
• What is happening in the background?
Copyright © Seán Kennedy
Parallel Streams
• Be careful if order is important, as the order of thread
completion will determine the final result (not the order in the
original collection).
Copyright © Seán Kennedy