Skip to content

Get All Keys of Hashtable in Java Example

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.

Once we get an enumeration of the keys, we can iterate all the keys using the hasMoreElements and nextElement methods of the enumeration.

Output

2. Using the keySet method

The Hashtable keySet method returns a Set view of all the keys of the hash table object.

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.

Output

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

About the author

Leave a Reply

Your email address will not be published.