Introduction to Parallel Streams API in Java

What are Parallel Streams in Java?

Parallel Streams is a feature that got introduced together with regular Streams, as part of Java 8.

Parallel Stream splits the source of data into multiple parts. It is meant for utilizing multiple cores of the processor.
After splitting the source, the parts are processed parallelly on separate cores and we get the combined result as an output.

Note: The order of execution is not guaranteed, we can not control it.
We have to be careful if we want to use them. First of all, we need to think about if the order of execution is important to us, or the order of processed elements in a Stream

How to create a Parallel Stream in Java?

We can create it in two ways:

  1. Using parallel() method from the BaseStream class – returns Parallel Stream equivalent to the original.

  2. Using parallelStream() method from the Collection class – returns the Parallel Stream with Collection as the source.


Let’s create Parallel Streams in both ways and compare them to the regular Streams:

Example 1:
Using the parallel() method:

class Test {

  public static void main(String[] args) {
    System.out.println("Normal Stream...");
    IntStream integers = IntStream.rangeClosed(1, 10);
    integers.forEach(num -> System.out.print(num + " "));


    System.out.println("Parallel Stream...");
    IntStream integers2 = IntStream.rangeClosed(1, 10);
    integers2.parallel().forEach(num -> System.out.print(num + " "));

Output: Normal Stream... 1 2 3 4 5 6 7 8 9 10 Parallel Stream... 7 6 9 10 8 3 5 4 2 1

Example 2:
Using the parallelStream() method:

class Test {

  public static void main(String[] args) {
    List<String> cities = new ArrayList<>(Arrays.asList("Bern", "Paris", "New York", "Tokyo", "Hong Kong", "Boston",
            "Berlin", "London", "Belgrade", "Monte Carlo", "Budapest", "Los Angeles", "Prague"));

    System.out.println("Normal Stream..."); -> System.out.print(city + " "));


    System.out.println("Parallel Stream...");
    cities.parallelStream().forEach(city -> System.out.print(city + " "));

Output: Normal Stream... Bern Paris New York Tokyo Hong Kong Boston Berlin London Belgrade Monte Carlo Budapest Los Angeles Prague Parallel Stream... London Belgrade Berlin Los Angeles Prague Budapest Monte Carlo Tokyo Boston Hong Kong Paris New York Bern

You see how the order of execution is different when comparing the normal Streams with Parallel Streams.
If we run the above programs a couple of more times, we will get different results from the Parallel Streams execution.

That’s it!


Leave a Reply

Your email address will not be published.