How to Browse a HashSet in Java

Java offers 3 ways to navigate through HashSet in Java:
  1. Foreach Loop
  2. While loop with Iterator
  3. While loop with  java.util.Enumeration
The following example gathers the 3 cases without Iterator or with Iterator and prints the results:

import java.util.Collections; 
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;

public class parcours_hashset {

public static void main(String[] args) {

HashSet< String> hset = new HashSet< String> ();

hset.add("he1");
hset.add("he2");
hset.add("he3");

/*Advanced For Loop*/
System.out.println("Advanced For Loop");
for(String s: hset)
System.out.println(s);

/*While+Iterator Loop*/
System.out.println("While+Iterator Loop");
Iterator it = hset.iterator();
while(it.hasNext())
System.out.println(it.next());

/*Enumeration*/
System.out.println("While+Enumeration Loop");
// retrieve the Enumeration
Enumeration enumeration = Collections.enumeration(hset);

// read through HashSet
while(enumeration.hasMoreElements())
System.out.println(enumeration.nextElement());
}
}
Let's see what happens by running this program:

Loop for advanced
he3
he1
he2
While+Iterator
he3
he1< br />he2
While+Enumeration Loop
he3
he1
he2
The iterator() is used to get an iterator through the elements of the HashSet or Set. Elements are returned mixed and without any specific order.

The interface java.util.Enumeration returns an object that generates a series of elements and uses two methods: hasMoreElements() to check if there are any more elements, if so, it retrieves the following element with the method nextElement().

References:
java.util.HashSet.iterator() Method
JavaDoc:  Enumeration Interface< E>