Write a Java program to Traverse over the elements of the hashset


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

Inside the main method, a new instance of the HashSet class is created using the constructor: HashSet h_set = new HashSet();. The specifies the type of elements that will be stored in the HashSet, which in this case is a string. After that, several elements are added to the HashSet using the add() method. The elements added are "Blue", "Green", "Black", "Orange", "White", "Pink", and "Yellow".

Next, the program creates an Iterator object using the iterator() method of the HashSet. The Iterator interface provides methods to iterate over the elements of a collection. The program then enters a while loop using the while keyword and the condition it.hasNext(), which checks if there is another element in the HashSet.

Inside the while loop, the program retrieves the next element from the HashSet using the next() method of the Iterator object. The next() method returns the next element and advances the iterator's position.

Source Code

import java.util.*;
 
public class Traverse_Elements
{
	public static void main(String args[])
	{
		HashSet <String> h_set= new HashSet <String>();
		h_set.add("Blue");
		h_set.add("Green");
		h_set.add("Black");
		h_set.add("Orange");
		h_set.add("White");
		h_set.add("Pink");
		h_set.add("Yellow");
 
		//Creating object of Iterator class
 
		Iterator it = h_set.iterator();
 
		System.out.println("Printing out hashset using iterator..");
 
		while (it.hasNext())
		{
			System.out.println(it.next());
		}
	}
}

Output

Printing out hashset using iterator..
White
Pink
Blue
Yellow
Black
Orange
Green

Example Programs