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

Definition:

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.

Syntax:

Stream<T> parallel()

Parameters:

None

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;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

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 = numbers.stream()
                                .parallel() // Convert the stream to parallel
                                .filter(n -> n % 2 == 0)
                                .mapToInt(Integer::intValue)
                                .map(n -> n * n)
                                .sum();

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

Output:

Sum of squares of even numbers: 167083500

Explanation:

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.

Comments