This example shows how to get all keys stored in the Hashtable in Java. This example also shows how to get all Hashtable keys using the keys method and keySet method.
How to get all keys of the Hashtable in Java?
There are a couple of ways using which we can get all the keys of the hash table.
1. Using the keys method
The Hashtable keys
method returns an enumeration of all the keys contained in this hashtable object.
1 |
public Enumeration<K> keys() |
Once we get an enumeration of the keys, we can iterate all the keys using the hasMoreElements
and nextElement
methods of the enumeration.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
import java.util.Enumeration; import java.util.Hashtable; public class HashtableGetAllKeysExample { public static void main(String[] args) { Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); /* * To get all keys stored in the hashtable * use the keys method */ Enumeration<Integer> keys = hashtable.keys(); //iterate while( keys.hasMoreElements() ){ System.out.println( keys.nextElement() ); } } } |
Output
1 2 3 |
3 2 1 |
2. Using the keySet method
The Hashtable keySet
method returns a Set view of all the keys of the hash table object.
1 |
public Set<K> keySet() |
The Set object containing the keys returned by this method is a view that is backed by the original hashtable object. That means any changes you make to this set will be reflected in the original hashtable object, and vice versa.
We can get the iterator from this Set object using the iterator
method. Once we get an iterator, we can iterate through it using the hasNext
and the next
methods as given below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
Hashtable<Integer, String> hashtable = new Hashtable<Integer, String>(); hashtable.put(1, "One"); hashtable.put(2, "Two"); hashtable.put(3, "Three"); /* * We can also use the keySet method to * get a Set view of all the keys */ Set<Integer> keys = hashtable.keySet(); //get an iterator Iterator<Integer> itr = keys.iterator(); //iterator while( itr.hasNext() ){ System.out.println( itr.next() ); } |
Output
1 2 3 |
3 2 1 |
Difference between keys and keySet method:
While both of these methods return all the keys of the hashtable object, there are some differences between these methods.
The keys
method is declared as an abstract method in the Dictionary class. The keySet
method was defined in Java 2 when the Hashtable class implemented the Map interface.
We can get an iterator for the key set and remove elements from the hashtable while iterating, while we cannot remove elements while iterating using the Enumeration obtained from the keys
method.
This example is a part of the Hashtable in Java Tutorial with Examples.
Please let me know your views in the comments section below.
References:
Java 8 Hashtable Documentation