Chapter 5. Parallel Streams

5.1.  Develop code that uses parallel streams

[Note]

Parallel Streams

Streams can be sequential or parallel. Operations on a sequential stream are processed in serial using one thread. Operations on a parallel stream are processed in parallel using multiple threads. You do not need to take additional steps to process streams because they are sequential or parallel. All you need to do is call the appropriate method that produces sequential or parallel stream. Everything else is taken care of by the Streams API

Most of the methods in the Streams API produce sequential streams by default. To produce a parallel stream from a collection such as a List or a Set, you need to call the parallelStream() method of the Collection interface.

Use the parallel() method on a stream to convert a sequential stream into a parallel stream. Conversely, use the sequential() method on a stream to convert a parallel stream into a sequential stream.

The following snippet of code shows serial processing of the stream pipeline because the stream is sequential:


Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));

System.out.println("Sequential Stream: ");
listOfIntegers
    .stream()
    .forEach(e -> System.out.print(e + " "));

					

output is:

Sequential Stream:
1 2 3 4 5 6 7 8
					

The following snippet of code shows parallel processing of the stream pipeline because the stream is parallel:


Integer[] intArray = {1, 2, 3, 4, 5, 6, 7, 8};
List<Integer> listOfIntegers = new ArrayList<>(Arrays.asList(intArray));

System.out.println("Parallel Stream: ");
listOfIntegers
    .stream()
    .parallel()
    .forEach(e -> System.out.print(e + " "));

					

output is (every time new order):

Parallel Stream:
6 5 7 4 2 1 8 3
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Exam 1Z0-810: Upgrade to Java SE 8 Programmer Quiz