Java Stream parallel()

In this guide, you will learn about the Stream parallel() method in Java programming and how to use it with an example.

1. Stream parallel() Method Overview


The Stream.parallel() method returns an equivalent stream that is parallel. This allows the operations on the stream to be executed in parallel, potentially utilizing multiple cores of the CPU.


Stream<T> parallel()



Key Points:

- The parallel stream leverages the Fork/Join framework in Java, which helps in utilizing multiple cores of the CPU.

- Even though the stream has been turned parallel, it does not mean every operation will be executed in parallel. The underlying framework decides which tasks to run in parallel based on the size and characteristics of the task.

- Once a stream is turned parallel, all the subsequent operations on it (unless otherwise specified) will be parallel operations.

- It's important to be cautious while using parallel streams, especially with shared mutable data, to avoid concurrency issues.

- The order of processing elements may not be in the original order when using parallel streams.

- Not all tasks benefit from parallelization; for some tasks, the overhead of parallelization can make the task slower. Therefore, profiling and understanding the nature of the task is essential.

2. Stream parallel() Method Example

import java.util.List;

public class StreamParallelExample {
    public static void main(String[] args) {
        List<Integer> numbers = IntStream.rangeClosed(1, 1000).boxed().collect(Collectors.toList());

        // Process the numbers using a parallel stream
        long squareSum =
                                .parallel() // Convert the stream to parallel
                                .filter(n -> n % 2 == 0)
                                .map(n -> n * n)

        System.out.println("Sum of squares of even numbers: " + squareSum);


Sum of squares of even numbers: 167083500


In the provided example: 

We first create a list of numbers from 1 to 1000. 

We then process these numbers using a parallel stream to compute the sum of the squares of even numbers. 

By turning the stream into a parallel stream, we allow the operations (filtering and mapping) to be potentially executed in parallel, taking advantage of multiple cores of the CPU. 

Finally, the result (sum of squares of even numbers) is printed.