Open In App

How to Perform Parallel Processing on Arrays in Java Using Streams?

In Java, parallel processing helps to increase overall performance. Arrays may be processed in parallel in Java by using Streams API. When working with big datasets or computationally demanding tasks, this is very helpful.

In this article, we will learn how to perform parallel processing on arrays in Java using streams.



Syntax for parallel processing on arrays using streams:

// to enable parallel processing
// convert an array to a stream Arrays.stream(array) .parallel()

Program to Perform Parallel Processing on Arrays Using Streams in Java

Let’s look at an example where we wish to do certain actions on each member of an integer array in parallel.




// Java Program to Perform Parallel Processing
// On Arrays Using Streams
import java.util.Arrays;
  
// Driver Class
public class ParallelProcessingExample 
{
      // Main Function
    public static void main(String[] args) 
    {
        // Create an array
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  
        // Convert the array to a stream
        Arrays.stream(numbers)
                  
                // Use parallel() to enable parallel processing
                .parallel()
  
                // Perform operations on each element
                .map(number -> number * 2)
  
                // Print the result
                .forEach(System.out::println);
    }
}

Output

14
12
18
20
16
6
10
8
4
2

Explanation of the above Program:

Article Tags :