It's not easy to get key from value in Hashtable or HashMap, as compared to getting value from key, because Hash Map or Hashtable doesn't enforce one to one mapping between key and value inside Map in Java. infact Map allows same value to be mapped against multiple keys inside HashMap, Hashtable or any other Map implementation. What you have in your kitty is Hashtable.containsValue(String value) or Hashtable.containsKey(String key) to check whether key or value exists in Hashtable or not, but some time we want to retrieve value from Map corresponding to any key and there is no API method to do in Map. We can still do this, but it highly depends data in your Map because Hashtable and HashMap both allows duplicate values mapped to different key. In this Java tutorial, we will see example of how to get key from value in Hashtable in Java.
Java - Key from Value in Map
There are essentially two ways to find key from values in Map, one is without using any third party library, and other is using third party library like Google collection or commons collections which provides bi directional Maps. Though most of the time projects already use these utility libraries, so its better to use them if you already using it; but just because you need to find key from value in Hashtable, adding new dependency doesn't make sense, especially if you can still do this by writing a function and iterating over Map in Java. In next section we will code example of retrieving value from key in hashtable as well as in hashmap.
Key from Value Hashtable HashMap Example
If you are using bi-directional Map e.g. BiMap (http://google-collections.googlecode.com/svn/trunk/javadoc/index.html?com/google/common/collect/BiMap.html ) from google collections you can do it in just one line :
That's all on how to get key from value in Hashtable and HashMap in Java. Though using google collection for this task is much clear and concise, it’s not always best option. Using JDK to find key from value in HashMap is better, if you know your map is one to one or one to many. Let me know, if you come across any other way of finding key from value in Hashtable or HashMap in Java.