How to Get Set of Keys from Java Hashtable


In this example, let us see how to get a Set of keys contained in Hashtable using keySet method of java Hashtable class.

Source Code

package com.beginner.examples;

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

public class GetSetViewOfKeysFromHashtable {

	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 Set of keys contained in Hashtable using keySet() method of Hashtable.
		 */
		Set set = hashtable.keySet();
		//iterate through the Set of keys
		Iterator iterator = set.iterator();
		while(iterator.hasNext()) {
			System.out.println(iterator.next());
		}
			      
	}

}

Output:

3
2
1

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments