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
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.
Stream<E> parallelStream()
This method does not take any parameters.
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.
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 listlist.parallelStream().forEachOrdered(i -> System.out.println(i));}}
parallelStream()
method to print the elements. We print the elements in the same order as they appear in the list.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.