How to Iterate Through HashTable in Java?


The HashTable is a fundamental data structure that operates on the basis of key hashcodes without preserving the insertion order. It prohibits duplicate keys but allows for duplicate values.

Remarkably, it accommodates a wide range of objects for both keys and values, fostering heterogeneity. Null values for keys and values are not allowed, though, as doing so would cause a RunTimeException called a NullPointerException.

The HashTable implements the serializable and cloneable interfaces in terms of interfaces, but it fails to implement the RandomAccess interface.

Additionally, all the methods within the HashTable are synchronized, ensuring thread safety for HashTable objects.

When it comes to selecting a data structure for frequent search operations, the HashTable emerges as the optimal choice.

Methods Used

We can iterate through the hashtable in a variety of methods, including −

  • By means of Enumeration Interface

  • With the help of keySet() method and enhance for loop

  • With the help of keySet() of the Map and Iterator Interface

  • Utilising the Map's entrySet() method and enhanced for loop

  • With the help of entrySet() method of Map and Iterator interface

  • Utilising the Iterable.forEach() method from Java 8

Method 1: By means of Enumeration Interface

The java.util.Enumeration interface is a pre-defined interface that serves the purpose of retrieving data from variables within the collections framework. It allows for data retrieval in a forward direction only and does not support backward traversal. It's important to note that the Enumeration interface has been replaced by the iterator.

nextElement()

The code creates a Hashtable. The code then populates it with key-value pair. Then,it iterates via the keys to print their corresponding values in descending order of the keys.

Algorithm

  • Step 1 − Import the required Java classes: "java.util" and "java.util.Enumeration".

  • Step 2 − Declare a class named "TLP".

  • Step 3 − Define the main method inside the "TLP" class: public static void main(String[] args).

  • Step 4 − Create a new instance of the Hashtable class named "ht" to store integer keys and string values.

  • Step 5 − Add key-value pairs to the Hashtable "ht" using the put method:

  • Step 6 − Create a new Enumeration object named "e" by calling the keys() method on the Hashtable "ht".

  • Step 7 − Enter a while loop with the condition "e.hasMoreElements()" to iterate through the keys in the Hashtable.

  • Step 8 − Within the while loop, retrieve the next key from the Enumeration with the usage of the nextElement() method and assign it to the variable "key".

  • Step 9 − Print the output message to the console. You do this with the usage of the System.out.println() method.

  • Step 10 −Terminate the program

Example

import java.util.*;
import java.util.Enumeration;

// Main Class
public class TLP {

   public static void main(String[] args){

      Hashtable<Integer, String> ht = new Hashtable<>();
      ht.put(1, "Apple");
      ht.put(2, "Strawberry");
      ht.put(3, "Berry");
      ht.put(4, "Guava");
      ht.put(5, "Peach");

      Enumeration<Integer> e = ht.keys();

      while (e.hasMoreElements()) {
         int key = e.nextElement();
         System.out.println("Rank : " + key + "\t\t Name : " + ht.get(key));
      }
   }
}

Output

Rank : 5		 Name : Peach
Rank : 4		 Name : Guava
Rank : 3		 Name : Berry
Rank : 2		 Name : Strawberry
Rank : 1		 Name : Apple

Method 2: With the help of keySet() method and enhance for loop

keySet()

The code prints the countries and their corresponding capitals stored in the Hashtable, with each pair displayed in the format "Country : [country] Capital : [capital]". The countries and capitals are printed in the order they were added to the Hashtable.

Algorithm

  • Step 1 − Create a new Hashtable object called "ht" to store string keys and string values.

  • Step 2 − Add key-value pairs to the Hashtable "ht" using the put method:

  • Step 3 − Obtain the set of keys from the Hashtable using the keySet() method and store it in the Set variable "setOfCountries".

  • Step 4 − Iterate through each key in the Set using a for-each loop.

  • Step 5 − Inside the loop, assign the current key to the String variable "key".

  • Step 6 − Print the output message. We do this with the usage of the System.out.println() method

  • Step 7 − End the program

Example

import java.util.Hashtable;
import java.util.Set;

public class TLP {

   public static void main(String[] args) {

      Hashtable<String, String> ht = new Hashtable<String, String>(); 

      ht.put("India", "Delhi");
      ht.put("Russia", "Moscow");
      ht.put("Australia", "Canberra");
      ht.put("USA", "Washingtin DC");

      // getting keySet() into Set
      Set<String> setOfCountries = ht.keySet();

      // for-each loop
      for(String key : setOfCountries) {
         System.out.println("Country : "  + key + "\t\t Capital : "  + ht.get(key));
      }
   }
}

Output

Country : USA		 Capital : Washingtin DC
Country : Russia		 Capital : Moscow
Country : India		 Capital : Delhi
Country : Australia		 Capital : Canberra

Method 3: Using keySet() of the Map and Iterator Interface

hasNext()

The code first creates a hashtable of states and their names. Then, it iterates through the hashtable and prints each state and its name.

Algorithm

  • Step 1 − Create a hashtable called ht and initialize it with five key-value pairs.

  • Step 2 − Get the keySet() of the hashtable and store it in a set called setOfKeys.

  • Step 3 − Create an iterator called itr for the setOfKeys.

  • Step 4 − Loop through the setOfKeys using the itr iterator:

  • Step 5 − Get the next element in the set, which is an integer key.

  • Step 6 − Get the name associated with the key from the hashtable.

  • Step 7 − Print the state and name.

Example

import java.util.*;
import java.util.Iterator;
import java.util.Set;

public class TLP {

   // Main driver method
   public static void main(String[] args){
      Hashtable<Integer, String> ht = new Hashtable<>();

      ht.put(1, "Telangana");
      ht.put(2, "Karnataka");
      ht.put(3, "Delhi");
      ht.put(4, "Maharashtra");
      ht.put(5, "Rajasthan");

      Set<Integer> setOfKeys = ht.keySet();

      Iterator<Integer> itr = setOfKeys.iterator();

      while (itr.hasNext()) {
         int key = itr.next();
         System.out.println("State : " + key + "\t\t Name : " + ht.get(key));
      }
   }
}

Output

State : 5		 Name : Rajasthan
State : 4		 Name : Maharashtra
State : 3		 Name : Delhi
State : 2		 Name : Karnataka
State : 1		 Name : Telangana

Method 4: Using Map's entrySet() method and enhanced for loop

while()

The given code creates a Hashtable and populates it with key-value pairs representing fruits and their corresponding colors. It then iterates through the entries in the Hashtable and prints each fruit with its respective color. The output displays the fruits and colors in the order they were added to the Hashtable.

Algorithm

  • Step 1 − Create a hashtable called ht and initialize it with three key-value pairs.

  • Step 2 − Get the entrySet() of the hashtable.

  • Step 3 − Create a for-each loop that iterates through the entrySet().

  • Step 4 − In each iteration of the loop, get the next element in the entrySet(), which is a Map.Entry object.

  • Step 5 − Get the fruit and color from the Map.Entry object.

  • Step 6 − Print the fruit and color.

Example

package in.bench.resources.hashtable.iteration.ways;

import java.util.Hashtable;
import java.util.Map.Entry;
import java.util.Set;

public class TLP {
   public static void main(String[] args) {
      Hashtable<String, String> ht = new Hashtable<String, String>(); 

      ht.put("Apple", "Red");
      ht.put("Guava", "Green");
      ht.put("Lychee", "White");

      Set<Entry<String, String>> entrySet = ht.entrySet();

      for(Entry<String, String> entry1 : entrySet) {
         System.out.println("Fruit : "  + entry1.getKey() + "\t\t Color : "  + entry1.getValue());
      }
   }
}

Output

Fruit : Guava		 Color : Green
Fruit : Lychee		 Color : White
Fruit : Apple		 Color : Red

Method 5: With the help of entrySet() method of Map and Iterator interface

hasNext()

The given code creates a Hashtable and adds key-value pairs representing ranks and their corresponding names. It then iterates through the entries in the Hashtable using an iterator and prints each rank with its respective name. The output displays the ranks and names in ascending order of the keys.

Algorithm

  • Step 1 − Create a hashtable called ht and initialize it with five key-value pairs.

  • Step 2 − Get the entrySet() of the hashtable.

  • Step 3 − Create an iterator called itr for the entrySet().

  • Step 4 − Loop through the entrySet using the itr iterator:

  • Step 5 − Get the next element in the set, which is a Map.Entry object.

  • Step 6 − Get the rank and name from the Map.Entry object.

  • Step 7 − Print the rank and name.

Example

import java.util.*;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;

public class TLP {
   public static void main(String[] args){

      Hashtable<Integer, String> ht = new Hashtable<>();

      ht.put(1, "Project Management");
      ht.put(2, "Product Management");
      ht.put(3, "Software Development");
      ht.put(4, "Quality Assurance");
      ht.put(5, "Product Strategy");

      Set<Entry<Integer, String> > entrySet
      = ht.entrySet();

      Iterator<Entry<Integer, String> > itr
      = entrySet.iterator();

      while (itr.hasNext()) {
         Entry<Integer, String> entry = itr.next();
         System.out.println("Rank : " + entry.getKey() + "\t\t Name : " + entry.getValue());
      }
   }
}

Output

Rank : 5		 Name : Product Strategy
Rank : 4		 Name : Quality Assurance
Rank : 3		 Name : Software Development
Rank : 2		 Name : Product Management
Rank : 1		 Name : Project Management

Method 6: Utilising the Iterable.forEach() method from Java 8

forEach()

The given code creates a Hashtable and adds key-value pairs representing union territories and their corresponding names. It then iterates through the entries in the Hashtable using the forEach method and prints each union territory with its respective name. The output displays the union territories and names in the order they were added to the Hashtable.

Algorithm

  • Step 1 − Create a hashtable called ht and initialize it with three key-value pairs.

  • Step 2 − Use the forEach() method to traverse through the hashtable.

  • Step 4 − Get the key and value from the hashtable.

  • Step 5 − Print the union territory and name.

Example

import java.util.Hashtable;

public class TLP {

   public static void main(String[] args) {
      Hashtable<String, String> ht = new Hashtable<String, String>(); 

      ht.put("1", "Lakshadweep");
      ht.put("2", "Delhi");
      ht.put("3", "Pondicherry");

      ht.forEach((key, value)->System.out.println("Union Territory : " + key + "\t\t" + "Name : " + value));
   }
}

Output

Union Territory : 1		Name : Lakshadweep
Union Territory : 2		Name : Delhi
Union Territory : 3		Name : Pondicherry

Conclusion

There are various methods available to iterate through Hashtable in Java.From the usage of the Enumeration interface, the keySet() method with an enhanced for loop, the keySet() method with an Iterator interface, to the entrySet() method with an enhanced for loop, the entrySet() method with an Iterator interface, and the Iterable, we have discussed it all.

forEach() method introduced in Java 8. Each method offers flexibility and convenience in traversing the Hashtable based on specific requirements.

Updated on: 19-Oct-2023

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements