In the program, a HashSet named h_set is created and populated with some elements: "Blue", "Green", "Black", "Orange", "White", "Pink", and "Yellow".
The program then creates an Iterator object named it by calling the iterator() method on h_set. The Iterator allows us to traverse through the elements of the HashSet.
A while loop is used to iterate over the HashSet. The loop continues as long as the Iterator has more elements (it.hasNext() returns true). Within the loop, it.next() is called to retrieve the next element, and it is printed to the console. Finally, when there are no more elements in the HashSet, the loop terminates.
import java.util.*; import java.util.Iterator; public class Iterate_HashSet { 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"); Iterator<String> it = h_set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } }
White Pink Blue Yellow Black Orange Green
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions