What is the Collection.parallelStream() method in Java?

Overview

A parallel stream splits the processing of the elements in the stream into multiple threads. Processing the stream on a multi-core machine can improve the overall performance.

Streams use spliterators It defines the methods that are needed to obtain the elements of a parallel Stream. We can create and initialize a new spliterator object using the Spliterator interface. to implement parallelism. The spliterator can be parallelized to fetch elements in parallel from a collection.

By default, the spliterator returned by the stream() method is sequential. Therefore, if we try to modify it from different threads (parallel streams), we may get unexpected results. To overcome this issue, the Collection interface provides a new method parallelStream() in Java 8. It can be used to convert any sequential stream to a parallel stream.

Syntax

Stream<E> parallelStream()

Parameters

This method does not take any parameters.

Return value

This method returns a parallel stream based on the collection it is called. It may return a sequential stream. If the collection's size is 0 or 1, it might return the same collection on which it is called.

Example

import java.util.*;
class Main
{
public static void main (String[] args)
{
// Create a list of integers.
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
// using parallelStream to print the elements of the list
list.parallelStream().forEachOrdered(i -> System.out.println(i));
}
}

Explanation

  • Line 8: We create a list of integers.
  • Line11: We use the parallelStream() method to print the elements. We print the elements in the same order as they appear in the list.

Conclusion

A parallel stream is advantageous when working with a large list or collection as it can help improve performance by utilizing multiple processors. However, if the list or collection is small, using a parallel stream may not provide any performance benefit as parallel streams involve additional overhead.

Free Resources