HashSet Iterator Example : How to iterate through a HashSet/Set

In this tutorial we will see how to iterate HashSet in java. I have already shared how HashSet works internally in java which is an important java interview question. There are two ways to iterate through HashSet.

1. Iterate the HashSet using iterator.
2. Iterate the HashSet using for each loop.


1. Program for How to Iterate HashSet  Using Iterator



import java.util.*;

 public class HashSetIteratorExample {
    public static void main(String args[]) {
        
    // Declaring a HashSet
    HashSet<String> hashset = new HashSet<String>();
    // Add elements to HashSet
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    hashset.add("Papaya");
    hashset.add("Banana");    
    // Get iterator
    Iterator<String> it = hashset.iterator();
    // Show HashSet elements
    System.out.println("HashSet contains: ");
    while(it.hasNext()) {
      System.out.println(it.next());
    }
  }
} 


Output
HashSet contains:
Apple
Pear
Papaya
Orange
Banana


2.   Program for How to Iterate HashSet using for each loop



import java.util.*;

 public class HashSetIteratorExample {
    public static void main(String args[]) {
        
    // Declaring a HashSet
    HashSet<String> hashset = new HashSet<String>();
    // Add elements to HashSet
    hashset.add("Pear");
    hashset.add("Apple");
    hashset.add("Orange");
    hashset.add("Papaya");
    hashset.add("Banana");
    
    System.out.println("HashSet contains :");
    // Using for each loop
    for(String str : hashset){
        System.out.println(str);
    }
  }
 }


Output
HashSet contains :
Apple
Pear
Papaya
Orange
Banana




About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry