Perform Parallel Processing on Arrays in Java Using Parallel Streams
Java’s strong idea of parallel processing enables the simultaneous execution of tasks, enhancing application performance. Using Java’s parallel streams is one approach to do parallel processing on arrays. By using multi-core processors, parallel streams allow array items to be processed simultaneously, increasing efficiency.
In this article, we will learn how to perform parallel processing on arrays in Java using parallel streams.
Syntax:
DataType[] array = {}; //Create an array
Arrays.parallelSetAll(array, i -> performOperation(array[i])); // Perform parallel processing
Program to Perform Parallel Processing on Arrays in Java Using Parallel Streams
Let’s look at an example of utilizing parallel streams to square each member in an array.
Java
// Java Program to perform parallel streams to square each member in an array import java.util.Arrays; public class ParallelArrayProcessing { public static void main(String[] args) { // Create an array of integers int [] numbers = { 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 }; System.out.println( "Initial Array: " + Arrays.toString(numbers)); // Perform parallel processing using parallel streams Arrays.parallelSetAll(numbers, i -> performOperation(numbers[i])); // Display the modified array after parallel processing System.out.println( "Modified Array: " + Arrays.toString(numbers)); } // Example operation to be performed on each element of the array private static int performOperation( int value) { // In this example, let's square each element return value * value; } } |
Output
Initial Array: [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] Modified Array: [441, 484, 529, 576, 625, 676, 729, 784, 841, 900]
Explanation of the Program:
- In the above program, we have created an array of integers.
- Parallel processing is then applied using
Arrays.parallelSetAll().
- Here each element is modified based on the specified operation(in this case, squaring each element).
- Finally, the modified array is printed.