How to Iterate Through HashTable in Java?

24 Oct, 2021
HashTable is an underlying data structure where the insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. Value null is not allowed for both key and value otherwise we will get RunTimeException saying NullPointerException. It implements serializable and cloneable interfaces but not RandomAccess. Every method inside it is synchronized and hence HashTable objects are thread-safe. HashTable is the best choice if our frequent operation is search operation.
Methods:
There are various ways by which we can iterate through the HashTable which are as follows:
Using Enumeration InterfaceUsing keySet() method of Map and Enhance for loopUsing keySet() method of Map and Iterator InterfaceUsing entrySet() method of Map and enhanced for loopUsing entrySet() method of Map and  Iterator interfaceUsing Iterable.forEach() method  from version Java 8
Using Enumeration Interface
Using keySet() method of Map and Enhance for loop
Using keySet() method of Map and Iterator Interface
Using entrySet() method of Map and enhanced for loop
Using entrySet() method of Map and  Iterator interface
Using Iterable.forEach() method  from version Java 8
Now let us discuss the internal implementation of all methods one by one in detail to get a better understanding of iteration through HashTable
Method 1: Using Enumeration Interface
java.util.Enumeration interface is one of the predefined interfaces, whose object is used for retrieving the data from collections framework variable. In a forward direction only and not in the backward direction. This interface has been superseded by an iterator.
Java
// Java Program to Iterate through HashTable// using enumeration interface // Importing required packagesimport java.util.*;import java.util.Enumeration; // MAin Classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating Hashtable object where key is of Integer        // type and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to HashTable object        // Custom input entries        ht.put(1, "Ram");        ht.put(2, "Shyam");        ht.put(3, "Bijay");        ht.put(4, "Hritik");        ht.put(5, "Piyush");         // Creating  Enumeration interface        // and get keys() from Hashtable        Enumeration<Integer> e = ht.keys();         // Iterating through the Hashtable        // object         // Checking for next element in Hashtable object        // with the help of hasMoreElements() method        while (e.hasMoreElements()) {             // Getting the key of a particular entry            int key = e.nextElement();             // Print and display the Rank and Name            System.out.println("Rank : " + key                               + "\t\t Name : "                               + ht.get(key));        }    }}
Rank : 5         Name : Piyush
Rank : 4         Name : Hritik
Rank : 3         Name : Bijay
Rank : 2         Name : Shyam
Rank : 1         Name : Ram
Method 2: Using keySet() method of Map and Enhance for loop
The java.util.HashMap.keySet() method in Java is used to create a set out of the key elements contained in the hash map. It basically returns a set view of the keys, or we can create a new set and store the key elements in them. 
Java
// Java program to iterate through HashTable// using keySet method and enhance for-loop // Importing required packagesimport java.util.*;import java.util.Set; // Main Classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Creating Hashtable object in where key is of        // Integer type        // and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to HashTable object        // custom entries        ht.put(1, "Java");        ht.put(2, "Scala");        ht.put(3, "Python");        ht.put(4, "Pearl");        ht.put(5, "R");         // Getting keySets of Hashtable and        // storing it into Set        Set<Integer> setOfKeys = ht.keySet();         // Iterating through the Hashtable        // object using for-Each loop        for (Integer key : setOfKeys) {            // Print and display the Rank and Name            System.out.println("Rank : " + key                               + "\t\t Name : "                               + ht.get(key));        }    }}
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java
Method 3: Using keySet( ) method of Map and Iterator Interface
Again we will be using the same method as been implemented in the above example but here for iteration we will be using the Iterable interface 
Java
// Java program to iterate through HashTable// using keySet method and Iterator Interface // Importing required librariesimport java.util.*;import java.util.Iterator;import java.util.Set; // Main classclass GFG {     // Main driver method    public static void main(String[] args)    {        // Creating Hashtable object where key is of Integer        // type        // and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to HashTable object        // Custom input entries        ht.put(1, "Java");        ht.put(2, "Scala");        ht.put(3, "Python");        ht.put(4, "Pearl");        ht.put(5, "R");         // Getting keySets of Hashtable and        // storing it into Set        Set<Integer> setOfKeys = ht.keySet();         // Creating an Iterator object to        // iterate over the given Hashtable        Iterator<Integer> itr = setOfKeys.iterator();         // Iterating through the Hashtable object        // Checking for next element using hasNext() method        while (itr.hasNext()) {             // Getting key of a particular entry            int key = itr.next();             // Print and display the Rank and Name            System.out.println("Rank : " + key                               + "\t\t Name : "                               + ht.get(key));        }    }}
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java
Method 4: Using entrySet() method of Map and enhanced for loop
The java.util.HashMap.entrySet() method in Java is used to create a set out of the same elements contained in the hash map. It basically returns a set view of the hash map, or we can create a new set and store the map elements into them. 
Java
// Java program to iterate through HashTable// using entrySet method and enhance for-loop // Importing required librariesimport java.util.*;import java.util.Map.Entry;import java.util.Set;// Main Classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating Hashtable object where key is of Integer        // type and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to HashTable object        // Custom input entries        ht.put(1, "Java");        ht.put(2, "Scala");        ht.put(3, "Python");        ht.put(4, "Pearl");        ht.put(5, "R");         // Storing all entries of Hashtable        // in a Set using entrySet() method        Set<Entry<Integer, String> > entrySet            = ht.entrySet();         // Iterating through the Hashtable object        // using for-each loop        for (Entry<Integer, String> entry : entrySet) {             // print ad display the Rank and Name            System.out.println("Rank : " + entry.getKey()                               + "\t\t Name : "                               + entry.getValue());        }    }}
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java
Method 5: Using entrySet() method of Map and  Iterator interface
Again we will be using the same method as been implemented in the above example but here for iteration we will be using the Iterable interface 
Java
// Java program to iterate through hashtable using// entrySet method and Iterator interface // Importing required librariesimport java.util.*;import java.util.Iterator;import java.util.Map.Entry;import java.util.Set; // Main Classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating Hashtable object where key is of Integer        // type        // and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to Hashtable object        // Custom input entries        ht.put(1, "Java");        ht.put(2, "Scala");        ht.put(3, "Python");        ht.put(4, "Pearl");        ht.put(5, "R");         // Storing all entries of Hashtable in a Set        // using entrySet() method        Set<Entry<Integer, String> > entrySet            = ht.entrySet();         // Creating an Iterator object to        // iterate over the given Hashtable        Iterator<Entry<Integer, String> > itr            = entrySet.iterator();         // Iterating through the Hashtable object        // using iterator         // Checking for next element        // using hasNext() method        while (itr.hasNext()) {             // Getting a particular entry of HashTable            Entry<Integer, String> entry = itr.next();             // Print and display the Rank and Name            System.out.println("Rank : " + entry.getKey()                               + "\t\t Name : "                               + entry.getValue());        }    }}
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java
6. Using Iterable.forEach() method  from version Java 8
With the coming of havoc new features in version, 8. It has been Quite a while since Java 8 released. With the release, they have improved some existing APIs and added few new features. One of them is forEach() method in java.lang.Iterable Interface. 
Java
// Java program to iterate through HashTable// using Iterable forEach()method of java 8 // Import required librariesimport java.util.*; // Main Classclass GFG {     // Main driver method    public static void main(String[] args)    {         // Creating Hashtable object in where key is of        // Integer type        // and value is of String type        Hashtable<Integer, String> ht = new Hashtable<>();         // Putting key-value pairs to HashTable object        // Custom input entries        ht.put(1, "Java");        ht.put(2, "Scala");        ht.put(3, "Python");        ht.put(4, "Ruby");        ht.put(5, "R");         // Iterating through Hashtable using        // forEach loop of java 8        ht.forEach((key, value)                       -> System.out.println(                           "Rank : " + key                           + "\t\t Name : " + value));    }}
Rank : 1         Name : Java
Rank : 2         Name : Scala
Rank : 3         Name : Python
Rank : 4         Name : Ruby
Rank : 5         Name : R
 
anikaseth98
arorakashish0911
gulshankumarar231
sooda367
adnanirshad158
Java-Collections
Java-HashTable
Picked
Java
Java Programs
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.