How to Iterate Over Keys of Java Hashtable


In this example, let us see how to iterate through the keys contained in the Hashtable object.

Source Code

package com.beginner.examples;

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

public class IterateThroughKeysOfHashtable {

	public static void main(String[] args) {
		
		//create Hashtable.
		Hashtable hashtable = new Hashtable();
		
		hashtable.put("1","Alice");
		hashtable.put("2","Bob");
		hashtable.put("3","Jack");
		
		/*
		 * get Enumeration of keys contained in Hashtable using Enumeration keys() method of Hashtable.
		 */
		Enumeration enumeration = hashtable.keys();
		//iterate through Hashtable keys Enumeration
		while(enumeration.hasMoreElements()) {
			System.out.println(enumeration.nextElement());
		}
		  
	}

}

Output:

3
2
1

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments