Parallel Data Processing in Java

Java 8Server Side ProgrammingProgramming

The ‘Stream’ interface in Java, which was introduced in Java 8, is used to manipulate data collections in a declarative fashion. Stream interface can also be used to execute processes in parallel, without making the process too complicated. This means, a sequential stream can be declaratively turned into a parallel stream.

A parallel stream can be defined as a stream that splits the data collection elements into multiple streams. Every stream is assigned to a separate chunk and it is associated with a different thread. The work is divided between multiple threads, with the help of multiprocessors. This way, the CPU resources are efficiently used, and it is kept busy. A sequential stream can be converted into a parallel stream by prefixing the keyword ‘parallel’ to it. Following is an example −


 Live Demo

import java.util.Collections.*;
public class Demo {
   static long sum_in_parallel(long n) {
      return Stream.iterate(1L, i->i + 1).limit(n).parallel().reduce(0L, Long::sum);
   public static void main(String[] args) {
      long c = sum_in_parallel(23);
      System.out.println("Sum, when computed in parallel is " + c);


Sum, when computed in parallel is 276

A class named Demo contains a function named ‘sum_in_parallel’ that takes a long integer as a parameter and returns the stream which can be iterated in parallel. In the main function, the ‘sum_in_parallel’ is called by passing a value, and this output is printed on the screen.

Published on 14-Sep-2020 12:43:59