• Java Data Structures Tutorial

Loop through a hash table



The HashTable class provides a method named keys() which returns an enumeration object holding the all keys in the hash table.

Using this method get the keys and retrieve the value of each key using the get() method.

The hasMoreElements() method of the Enumeration (interface) returns true if the enumeration object has more elements. You can use this method to run the loop.

Example

import java.util.Enumeration;
import java.util.Hashtable;

public class Loopthrough {
   public static void main(String args[]) {
      String str;
      Hashtable hashTable = new Hashtable();
      hashTable.put("Ram", 94.6);
      hashTable.put("Rahim", 92);
      hashTable.put("Robert", 85);
      hashTable.put("Roja", 93);
      hashTable.put("Raja", 75);
      
      Enumeration keys = hashTable.keys();
      System.out.println("Contents of the hash table are :");
      
      while(keys.hasMoreElements()) {
         str = (String) keys.nextElement();
         System.out.println(str + ": " + hashTable.get(str));
      }       
   }
}

Output

Contents of the hash table are :
Rahim: 92
Roja: 93
Raja: 75
Ram: 94.6
Robert: 85
Advertisements