Minggu, 29 Juni 2014

How to get Key from Value in Hashtable, HashMap or Map in Java








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
value
s 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



How to get key from value in Java HashMap example tutorialThere 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






import java.util.HashMap;


import java.util.HashSet;


import java.util.Hashtable;


import java.util.Map;


import java.util.Set;





/**


 * Java program to get key from value in Java
HashMap, Hashtable and Map.


 *


 * @author
java67


 */


public
class KeyFromValueExample {





public
static void
main(String args[]) {


       


        //how to
get key from value in hashtable in Java


        Hashtable table = new Hashtable();


        table.put("Sony", "Bravia");


        table.put("Samsung", "Galaxy");


        table.put("Nokia", "Lumia");


      


        System.out.println("does hash table has Lumia
as value : "
+ table.containsValue("Lumia"));


        System.out.println("does hash table Lumia as
key : "
+ table.containsKey("Lumia"));


      


        //finding
key corresponding to value in hashtable - one to one mapping


        String key= null;


        String value="Lumia";


        for(Map.Entry entry: table.entrySet()){


            if(value.equals(entry.getValue())){


                key = entry.getKey();


                break; //breaking because its one to one map


            }


        }


        System.out.println("got key from value in
hashtable key:  "
+ key +" value: " + value);


      


        //finding
key corresponding to value in hashtable - one to many mapping


        table.put("HTC", "Lumia");


        Set keys = new HashSet();


      


        for(Map.Entry entry: table.entrySet()){


            if(value.equals(entry.getValue())){


                keys.add(entry.getKey()); //no break, looping entire hashtable


            }


        }


        System.out.println("keys : " + keys +" corresponding to value in hash table:  "+ value);


      


      


        //how to
get from value in HashMap example - similar to Hashtable example


        HashMap map = new HashMap();


        map.put("one", 1);


        map.put("two", 2);


      


        //find
key from value in HashMap Java - one to one mapping


        Integer intValue=2;


        String strKey = null;


        for(Map.Entry entry: map.entrySet()){


            if(intValue.equals(entry.getValue())){


                strKey = entry.getKey();


                break; //breaking because its one to one map


            }


        }


      


        System.out.println("key from value in
hash table key:  "
+ strKey +" value: " + intValue);


    }


}





Output


does
hash table has Lumia as value
: true


does
hash table has Lumia as key
: false


got key
from value in hashtable key
:  Nokia value: Lumia


keys : [Nokia, HTC] corresponding to value in
hash talbe
:  Lumia


key from
value in hash table key
:  two value: 2









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 :






bidirMap.inverse().get(value)






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.





























Source:http://javarevisited.blogspot.com/2013/02/how-to-get-key-from-value-in-hashtable.html

Tidak ada komentar:

Posting Komentar