Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

Collection.parallelStream()

Returns a parallel stream: elements are processed in several threads at once.

Available since: Java 8

Syntax

default Stream<E> parallelStream()

Return value

Stream<E>A stream that may run in parallel.

Examples

A sum of squares — the result is the same as with an ordinary stream:

void main() {
    List<Integer> numbers = IntStream.rangeClosed(1, 1_000).boxed().toList();
    long sum = numbers.parallelStream()
        .mapToLong(n -> (long) n * n)
        .sum();
    IO.println(sum);
}

Output:

333833500

The order of forEach() in a parallel stream is unpredictable; forEachOrdered() keeps it:

void main() {
    List<Integer> list = List.of(1, 2, 3, 4, 5);
    list.parallelStream().forEach(n -> IO.print(n + " "));
    IO.println("");
    list.parallelStream().forEachOrdered(n -> IO.print(n + " "));
    IO.println("");
}

Output:

2 5 3 4 1 
1 2 3 4 5

Notes

Parallel streams use the shared ForkJoinPool.commonPool() with about as many threads as cores. They pay off only on large data and heavy computation; for small lists and I/O a parallel stream is usually slower. Do not modify shared variables or ordinary collections from the lambda — gather the result with collect(), reduce() or sum(). An ordinary stream becomes parallel with parallel().

See also

In the tutorial

  • Parallel streams — parallelStream and parallel in Java: how a stream is split across processor cores, when it speeds things up, ordering and forEachOrdered, and the danger of shared mutable state.

Thanks for reading!

Donate to the site — we work hard for you.