How to use Hashtable.keys method in Java?

What is a HashTable?

A HashTable is a collection of key-value pairs. The object to be used as a key should implement the hashCode and equals methods, and the key and value should not be null.


You can read about the difference between HashTable and HashMap here.

What is the keys() method in Hashtable?

The keys method can get all the keys of the HashTable as an Enumeration object.

Syntax


public Enumeration<K> keys()

Parameters

This method doesn’t take any arguments.

Return value

The keys method returns an enumeration of the keys of the hashtable.

Code

The example below shows how to use the keys method.

import java.util.Hashtable;
import java.util.Enumeration;
class HashtableKeysExample {
public static void main( String args[] ) {
Hashtable<Integer, String> map = new Hashtable<>();
map.put(1, "one");
map.put(2, "two");
System.out.println("The map is :" + map );
Enumeration<Integer> keys = map.keys();
System.out.print("The keys are : ");
while(keys.hasMoreElements()) {
System.out.print(keys.nextElement() + ",");
}
}
}

Explanation

In the code above:

  • In line 1, we import the Hashtable class.

  • In line 6, we create a Hashtable object with the name map.

  • In lines 7 and 8, we use the put method to add two mappings ({1=one, 2=two}) to the map object.

  • In line 12, we use the keys method to get the keys of the Hashtable and store them in the keys variable.

    Then, we use the while loop hasMoreElements, and nextElement to print the keys Enumeration object.