Horje
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()
  • 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

// 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:

  • 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.



Reffered: https://www.geeksforgeeks.org


Java

Related
How to Handle Concurrent Access and Modification of a TreeMap Using Concurrent Collections in Java? How to Handle Concurrent Access and Modification of a TreeMap Using Concurrent Collections in Java?
How to Implement a Resizable Array in Java? How to Implement a Resizable Array in Java?
How to Extract a Specific Line from a Multi-Line String in Java? How to Extract a Specific Line from a Multi-Line String in Java?
How to Update the Value for an Existing Key in a TreeMap Using put()? How to Update the Value for an Existing Key in a TreeMap Using put()?
How to Get the File's Parent Directory in Java? How to Get the File's Parent Directory in Java?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14