How to Perform Parallel Processing on Arrays in Java Using Streams?
Last Updated :
14 Feb, 2024
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()
- parallel(): This function in Java Streams API introduces parallel processing. It enables the simultaneous execution of actions on many threads when applied to a stream.
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
import java.util.Arrays;
public class ParallelProcessingExample
{
public static void main(String[] args)
{
int [] numbers = { 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 };
Arrays.stream(numbers)
.parallel()
.map(number -> number * 2 )
.forEach(System.out::println);
}
}
|
Output
14
12
18
20
16
6
10
8
4
2
Explanation of the above Program:
- In the above program, first we have created an array.
- Then, we have converted the array to a stream.
- After that, we have used parallel() method to enable parallel processing.
- It performs operations on each element.
- At last, it prints the result.
Share your thoughts in the comments
Please Login to comment...