Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Collection.parallelStream(): parallel stream pipelines

Create a stream pipeline from a collection that can run in parallel. Learn why execution mode and result order are separate and when to measure performance.

Version: Java SE 21

Syntax

default Stream<E> parallelStream()

Stream<E> pipeline = collection.parallelStream();

Collection.parallelStream() is a no-argument default method on java.util.Collection<E>, available since Java 8. It returns a Stream<E> sourced from the collection. The default implementation creates a parallel stream from the collection's Spliterator<E>, but the contract permits a sequential return value. By contrast, stream() returns a sequential stream.

Intermediate operations such as map() are lazy: a terminal operation such as collect() triggers processing. Check isParallel() before the terminal operation to inspect the pipeline's mode, not how many threads will actually do the work. Do not reuse the same stream after a terminal operation.

The order of the result is not the order in which threads do the work. For a pipeline with a defined encounter order, such as a List source followed by map(), collect(Collectors.toList()) preserves that order. Collectors.toSet() does not promise it. Neither does forEach() on a parallel pipeline; if actions must follow encounter order, use forEachOrdered() on an ordered stream.

Do not modify a non-concurrent source collection while the pipeline is running. Use stateless lambdas and gather results with collect() instead of appending to a shared ArrayList from forEach(). Splitting work and merging results have a cost, so a small or cheap pipeline can be slower in parallel. Compare it with stream() on representative data.

Examples

import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = List.of(3, 1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13);

        List<Integer> doubled = numbers.parallelStream()
                .map(n -> n * 2)
                .collect(Collectors.toList());

        System.out.println(doubled);
    }
}

Result

[6, 2, 4, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26]

The pipeline doubles 13 numbers and collects them in input order. The `[6, 2, 4, …]` prefix shows that order was preserved, not sorted. The output proves neither that multiple threads ran nor that the pipeline was faster.

Related lessons

  • Java · Lesson 24 · Advanced · Version: 2
  • Java · Lesson 57 · Intermediate · Version: 2

Sources