Traverse through a HashSet in Java


HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage.

A hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code.

To traverse through a HashSet, you can use the Iterator in Java. At first, create a HashSet with string values −

HashSet<String> hashSet = new HashSet();
hashSet.add("Jack");
hashSet.add("Tom");
hashSet.add("David");
hashSet.add("John");
hashSet.add("Steve");

Now, traverse using Iterator −

Iterator<String> iterator = hashSet.iterator();
while(iterator.hasNext()){
   System.out.println(iterator.next());
}

Let us see a simple example wherein we have some HashSet elements and we would be traversing each of them and displaying −

Example

import java.util.*;
class Main{
   public static void main(String args[]){
      HashSet<String> hashSet = new HashSet();
      hashSet.add("Jack");
      hashSet.add("Tom");
      hashSet.add("David");
      hashSet.add("John");
      hashSet.add("Steve");
      hashSet.add("Kevin");
      hashSet.add("Ryan");
      hashSet.add("Lyn");
      Iterator<String> iterator = hashSet.iterator();
      System.out.println("HashSet elements...");
      while(iterator.hasNext()) {
         System.out.println(iterator.next());
      }
   }
}

Output

HashSet elements...
Lyn
Kevin
Tom
Ryan
Steve
David
John
Jack

Updated on: 23-Sep-2019

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements