Write a Java program to Print HashSet elements using parallelStream() method


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet. Next, the program defines a class called Using_ParallelStream. Inside the Using_ParallelStream class, the main method is declared and serves as the entry point for the program. It takes an array of strings (args) as input.

Within the main method, a HashSet called nums is created and initialized with Integer objects. The HashSet represents a set of numbers. After initializing nums with some elements using the add() method, the program proceeds to demonstrate the usage of parallel stream.

The program uses the parallelStream() method on the nums HashSet to obtain a parallel stream. The parallel stream allows for parallel processing of elements, potentially improving performance for large data sets. The forEach() method is then called on the parallel stream. The System.out::println method reference is passed as an argument to forEach(), which prints each element on a new line.

Finally, the program prints "HashSet Elements : " using the System.out.println() statement before printing the elements of the HashSet using the parallel stream.

Source Code

import java.util.*;
class Using_ParallelStream
{
	public static void main(String[] args)
	{
		HashSet <Integer> nums = new HashSet<Integer>();
		nums.add(10);
		nums.add(20);
		nums.add(30);
		nums.add(40);
		nums.add(50);
 
		System.out.println("HashSet Elements : ");
		nums.parallelStream().forEach(System.out::println);
	}
}

Output

HashSet Elements :
40
10
20
30
50

Example Programs