0Pricing
Java Academy · Lesson

Creating Parallel Streams

parallel() and parallelStream().

What Parallel Streams Do

A parallel stream splits its data and processes chunks on multiple threads, then combines results. The goal is faster throughput on large workloads.

import java.util.stream.IntStream;

public class Main {
    public static void main(String[] args) {
        int sum = IntStream.rangeClosed(1, 1000)
            .parallel()
            .sum();
        System.out.println(sum);
    }
}

parallel() on an Existing Stream

Calling parallel() turns a sequential stream into a parallel one. It can appear anywhere in the pipeline.

import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(1, 2, 3, 4, 5);
        int total = nums.stream()
            .parallel()
            .mapToInt(Integer::intValue)
            .sum();
        System.out.println(total);
    }
}

All lessons in this course

  1. Creating Parallel Streams
  2. When Parallelism Helps
  3. Thread Safety and Side Effects
  4. Common Pitfalls
← Back to Java Academy