Arrays In Java 8 – Stream Class And ParallelSort Method

Java 8 has been a Major Release in the History of Java. This Tutorial Explains Various Changes to Arrays in Java 8 like Streams Class And Parallel Sorting:

Many new features were introduced in this release as already discussed in our previous tutorial on “Java 8 Features”. Let us learn about Java 8 Stream Class and Parallel Sorting Method.

=> Watch Out The Simple Java Training Series Here.

Arrays in Java 8

Arrays In Java 8

Java8 introduced a few features specifically related to arrays.

It includes:

  • Streams for Arrays
  • Parallel Sorting

In this tutorial, we will discuss these two features of Java 8 in detail.

Java 8 Stream

Java 8 has added a stream class for arrays that improves the readability as well as the efficiency of arrays. Converting arrays to stream also increases the overall performance of the program.

In addition to this, you can also use the various Stream API methods that can simplify mapping, and filtering actions on arrays.

The following method overloads can be used to convert an array into a stream.

<T> Stream<T> stream(T[] array)
IntStream stream(int[] array)
LongStream stream(long[] array)
DoubleStream stream(double[] array)

The following program shows the implementation of using streams with arrays. This program shows a comparison of the Iterative approach and Streams approach. Later, the sum of the elements in the array is calculated using Iteration and Streams and the average is calculated.

import java.util.Arrays; 
class Main { 
     public static void main(String[] args) 
    { 
        int intArray[] = {5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100}; 

        //calculate sum using iterative method
       int sum = 0; 
       for (int i = 0; i <intArray.length; i++) 
           sum += intArray[i]; 
       System.out.println("Iteration approach : Average :" + 
                                    (sum / intArray.length)); 
         // sum using streams
         sum = Arrays.stream(intArray) // Step 1 
                  .sum(); // Step 2 
         System.out.println("Streams approach : Average " + 
                                   (sum / intArray.length)); 

        // print array elements from stream using forEach
        System.out.println("Array elements : "); 
        Arrays.stream(intArray) 
            .forEach(e->System.out.print(e + " ")); 
    } 
}

Output:

Implementation of using streams with arrays

The above output shows the average iteration and streams approach. As the elements are less, the average is the same but as elements in the array increase, the iterative approach becomes slower.

The next programming example shows how an array is converted to integer stream and then using the map method of the stream to map elements of the array to random values and then add these elements. The program then prints the sum of all the elements in the integer stream.

import java.util.Arrays; 
class Main { 
    public static void main(String[] args) 
    { 
        //declare array of ints
        int[] ints = new int[100];
        //fill array with value 10
        Arrays.fill(ints, 10);
        //maps array stream to random numbers and calculates sum of the elements
        int sum = Arrays.stream(ints)
                  .map(i -> (int) (Math.random() * i))
                  .sum();
        //print the sum
        System.out.println("The sum of the random array elements: " + sum);
    } 
}

Output:

Prints the sum of all the elements in the integer stream

We have used the map method that is provided by the Stream class in the above program. We also used the sum() method that adds the elements in the stream.

Java 8 parallelSort() Method

The method “parallelSort()” is introduced in Java 8. It is a method of java.util.Arrays class. The parallelSort method is used to sort an array in a parallel fashion. It uses the fork and join approach in which the arrays are forked into smaller units until each unit is easily manageable and then sorted individually.

Then the smaller units are joined together and this entire operation happens in parallel. One prime advantage of this parallelSort method is that it uses multithreading thereby making sorting faster and efficient.

The parallelSort () method has the following overloads:

public static void parallelSort (Object obj[])

The above method prototype is used to sort an array in ascending order.

public static void parallelSort (Object obj[], int fromIndex, int toIndex)

The above overload is used to sort elements in the specified range from ‘fromIndex’ to ‘toIndex’ in the array.

The following Java program demonstrates the parallelSort method to sort an array.

import java.util.Arrays; 

public class Main { 
    public static void main(String[] args) 
    { 
        // Creating an array 
        int numArray[] = { 54,34,25,13,65,37,85,47,26 }; 

        // print the original Array 
        System.out.print("Original Unsorted Array: "); 
        // iterate the array using streams
        Arrays.stream(numArray) 
            .forEach(num ->System.out.print(num + " ")); 
        System.out.println(); 

        // Using parallelSort() method to sort array
       Arrays.parallelSort(numArray); 

        // Print sorted Array 
       System.out.print("Array sorted using parallelSort: "); 
       Arrays.stream(numArray) 
            .forEach(num->System.out.print(num + " ")); 
    } 
}

Output:

parallelSort method to sort an array

In the above program, the input array is sorted using a parallelSort method and output is printed.

The next program compares the two sorting methods provided by Arrays class i.e. the sort () method which is a linear sorting and parallelSort () method. This program compares the time taken by each method to sort an array. The time is calculated for each iteration.

import java.util.Arrays;  
import java.util.Random;  

public class Main {  
     public static void main(String[] args)  {  
       // Create an array  
       int numArray[] = new int[100];  
       System.out.println("Iteration#" + "\t" + "Serial Sort :Time(in ns)" + "\t" + "Parallel Sort :Time(in ns)");        	
              // Iterating Loop till i = 1000  
        // with interval of 10  
      for (int i = 0; i < 100; i += 10) {  
              System.out.print(" " + (i / 10 + 1) + "\t\t\t");  
              // Array generation using random function  
            Random rand = new Random();  
               for (int j = 0; j < 100; j++) {  
                  numArray[j] = rand.nextInt();  
            }  
            // Arrays.sort() method: Start and End Time  
            long startTime = System.nanoTime();  

	 // Call Serial Sort method Arrays.sort
        Arrays.sort(numArray);  
          long endTime = System.nanoTime();  

            // Print Serial Sort results  
           System.out.print((endTime - startTime) + "\t\t\t");  

            // Arrays.parallelSort() start and end time
            startTime = System.nanoTime();  

            // call Parallel Sort method Arrays.parallelSort
           Arrays.parallelSort(numArray);  

           endTime = System.nanoTime();  
 
            // Print Parallel Sort results  
           System.out.println("\t" + (endTime - startTime));  
           System.out.println();  
        }  
    }  
}  

Output:

Compares the time taken by each method to sort an array

The above output shows the comparison of the time taken by the sort and parallelSort methods for each iteration. You can see the clear difference between the performance of sort and parallelSort method with the parallelSort method fairing much better than sort.

Frequently Asked Questions

Q #1) What is Arrays Stream in Java?

Answer: This is the stream method of Arrays class. This method stream (T[] array) returns a sequential stream from the array.

Q #2) What is Stream () in Java?

Answer: Stream () in Java was first introduced in Java 8. Stream class consists of the API used for processing collection objects including arrays.

Q #3) How does Java Stream work?

Answer: The APIs of Java stream has a mechanism that can convert collections like ArrayList, Arrays, etc. to stream. They also process each element of these streams in parallel using various methods provided and pass results.

Q #4) What is the purpose of the MAP method of Stream in Java 8?

Answer: The map method belongs to java.util.stream.Streams class. The map method applies a function to each element of a stream or maps it to a different value and transforms it.

Q #5) Is Stream faster than for loop Java?

Answer: Yes, especially the parallel streams. For Example, the parallelSort method of Arrays class that uses parallel streams is faster than the sequential sort method provided by the Arrays class.

Conclusion

Streams in Java is a new feature included since Java 8. Streams provide a string API whose methods can be used on collections in Java. In this tutorial, we have seen stream methods that work on Java arrays. We have also seen the other features that were added to Java arrays in Java 8 edition.

One of them is stream while the other is the parallelSort method that sorts an array in a parallel manner. This method is faster than the linear method sort, which was evident in the program where we compared both the methods.

=> Visit Here For The Exclusive Java Training Tutorial Series.