Course contentsShow
← Java
Lesson 1372 of 2,87031. Streams API: Creation and BasicsFree lesson

Sequential vs Parallel Streams

Learning that streams can execute sequentially or in parallel, with parallel streams leveraging multiple threads automatically.

Sequential vs Parallel Streams

What you'll learn: You'll understand the difference between sequential and parallel stream execution and when each mode is used.

The Core Idea

By default, streams execute sequentially—they process elements one at a time in a single thread, just like a traditional loop. However, streams can also run in parallel mode, automatically splitting the work across multiple threads to potentially speed up processing on multi-core processors.

Think of it like washing dishes: sequential processing is one person washing each dish in order, while parallel processing is multiple people dividing the stack and washing dishes simultaneously.

Sequential Streams (Default Behavior)

When you create a stream from a collection or array, it's sequential by default. Operations execute in order, on the current thread:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()  // Sequential by default
       .filter(n -> n % 2 == 0)
       .forEach(System.out::println);
// Processes: 1, then 2, then 3, then 4, then 5 (in order, one thread)

Parallel Streams

You can request parallel execution by calling .parallel() on a stream or using .parallelStream() when creating from a collection:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
numbers.parallelStream()  // Parallel execution
       .filter(n -> n % 2 == 0)
       .forEach(System.out::println);
// May process elements on multiple threads simultaneously

The Java runtime automatically manages thread allocation using the common fork-join pool—you don't manually create threads.

When to Choose

Sequential streams are simpler, predictable, and often sufficient. Parallel streams can improve performance for large datasets with computationally expensive operations, but add overhead and complexity.

Key Takeaway: Streams execute sequentially by default on a single thread, but can be made parallel to leverage multiple threads automatically—though parallelism isn't always faster for small or simple operations.