Java Language Parallel Stream


Example

Note: Before deciding which Stream to use please have a look at ParallelStream vs Sequential Stream behavior.

When you want to perform Stream operations concurrently, you could use either of these ways.

List<String> data = Arrays.asList("One", "Two", "Three", "Four", "Five");
Stream<String> aParallelStream = data.stream().parallel();

Or:

Stream<String> aParallelStream = data.parallelStream();

To execute the operations defined for the parallel stream, call a terminal operator:

aParallelStream.forEach(System.out::println);

(A possible) output from the parallel Stream:

Three
Four
One
Two
Five

The order might change as all the elements are processed in parallel (Which may make it faster). Use parallelStream when ordering does not matter.

Performance impact

In case networking is involved, parallel Streams may degrade the overall performance of an application because all parallel Streams use a common fork-join thread pool for the network.

On the other hand, parallel Streams may significantly improve performance in many other cases, depending of the number of available cores in the running CPU at the moment.