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


The program starts with the import statement import java.util.*;, which imports all classes from the java.util package, including HashSet and Spliterator.

  • The program defines a class called Using_Spliterator. Inside the Using_Spliterator 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 the Spliterator interface.
  • A Spliterator is obtained from the nums HashSet using the spliterator() method. The Spliterator interface provides methods for traversing and splitting elements of a collection in a parallel or sequential manner.
  • The program then uses the forEachRemaining() method of the Spliterator interface to iterate over the elements of the nums HashSet. The lambda expression (n) -> System.out.print(n+" ") is passed as an argument to the forEachRemaining() method, which prints each element followed by a space.
  • Finally, the program prints "HashSet Elements : " using the System.out.print() statement before printing the elements of the HashSet using the forEachRemaining() method.

Source Code

import java.util.*;
class Using_Spliterator
{
	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);
		nums.add(60);
		nums.add(70);
		nums.add(80);
		nums.add(90);
		nums.add(100);
 
		Spliterator <Integer> splt = nums.spliterator();
		System.out.print("HashSet Elements : ");
		splt.forEachRemaining((n) -> System.out.print(n+" "));
	}
}

Output

HashSet Elements : 80 50 20 100 70 40 10 90 60 30

Example Programs