How to use Hashtable.keys method in Java?
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
Hashtableclass. -
In line 6, we create a
Hashtableobject with the namemap. -
In lines 7 and 8, we use the
putmethod to add two mappings ({1=one, 2=two}) to themapobject. -
In line 12, we use the
keysmethod to get the keys of theHashtableand store them in thekeysvariable.Then, we use the
whileloop hasMoreElements, and nextElement to print thekeysEnumerationobject.