Skip to content

Get Hashtable Key by Value in Java Example

This example shows how to get the Hashtable key by value in Java. This example also shows how to get a Hashtable key from a value using entrySet and keySet methods.

How to get a Hashtable key from the value in Java?

The Hashtable class in Java maintains the mapping of keys to values, not the other way around. There is no direct way to get the key from value, however, there are a couple of workarounds using which we can get the key as given below.

1. Using the entrySet method

We can get all the entries of the Hashtable object, get an iterator using the iterator method and then iterate through hashtable entries to find the value.

Output

2. Using the keySet method

Instead of entries, we can also get Set of all keys from the Hashtable using the keySet method, iterate through it and compare values with the value we are interested in as given below.

Output

What if Hashtable has duplicate values mapped to many keys?

The hashtable allows one value mapped to many keys. In that case, you can return a List of keys instead of a single key as given below.

Output

Important Note:

Both of these approaches may not perform well if the hashtable has a large number of entries.

This example is a part of the Java Hashtable 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.