How to Use Enumeration to Display Elements of Hashtable in Java?
Prerequisite: Hashtable in Java
We can get the keys and values of a Hashtable as an Enumeration object. Using keys() and elements() method, we can obtain all keys and values respectively as an Enumeration object. Using Enumeration methods like hasMoreElements() and nextElement() we can read all keys and values corresponding to from a Hashtable.
Example 1:
Java
// Java program to demonstrate// getting values as an Enumeration import java.util.Enumeration;import java.util.Hashtable;import java.io.*; public class EnumerationOnKeys { public static void main(String[] args) { // initialize an object of Hashtable Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); // insert key-value pairs into hash table ht.put(1, "Geeks"); ht.put(2, "for"); ht.put(3, "Geeks"); // create an Enumeration object to read elements Enumeration e = ht.elements(); // print elements of hashtable using enumeration while (e.hasMoreElements()) { // print the current element System.out.println(e.nextElement()); } }} |
Geeks for Geeks
Example 2:
Java
// Java program to demonstrate// getting keys as an Enumeration import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create hashtable Hashtable<String, String> ht = new Hashtable<String, String>(); // put key-value pairs into hashtable ht.put("Name", "Rohan"); ht.put("Age", "23"); ht.put("Address", "India"); ht.put("Article", "GeeksforGeeks"); // create enumeration to store keys Enumeration<String> e = ht.keys(); // while keys are present while (e.hasMoreElements()) { // get key String key = e.nextElement(); // print key and value corresponding to that key System.out.println(key + ":" + ht.get(key)); } }} |
Name:Rohan Article:GeeksforGeeks Age:23 Address:India
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


