keys()
method in Hashtable
?The keys
method can get all the keys of the HashTable
as an Enumeration
object.
public Enumeration<K> keys()
This method doesn’t take any arguments.
The keys
method returns an enumeration
of the keys of the hashtable.
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() + ",");}}}
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.