Perform Parallel Processing on Arrays in Java Using Parallel Streams
Last Updated :
07 Feb, 2024
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
import java.util.Arrays;
public class ParallelArrayProcessing
{
public static void main(String[] args)
{
int [] numbers = { 21 , 22 , 23 , 24 , 25 , 26 , 27 , 28 , 29 , 30 };
System.out.println( "Initial Array: " + Arrays.toString(numbers));
Arrays.parallelSetAll(numbers, i -> performOperation(numbers[i]));
System.out.println( "Modified Array: " + Arrays.toString(numbers));
}
private static int performOperation( int value) {
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.
Share your thoughts in the comments
Please Login to comment...