Friday 29 March 2013

BiMap: A two-way Map in #android

A simple hashMap is used to keep key,value pairs. It is useful in situation where we need to lookup values by keys. e.g
        
HashMap<String, String> simplemap=new HashMap<String, String>();
        simplemap.put("name", "sohail");
        
        simplemap.get("name");


Above is the simple example of hashmap, where we put a key,value pair and then lookup using key. However, there are situations where we need reverse lookup i.e lookup by value. An example of such case can be a Map of the indexes of two lists, and we need to lookup one's index by other and vice versa. A map which can be looked-up by keys as well as values, is called BiMap provided by Guava.
We can use HashBiMap to create a bimap and then use its map.inverse function to get inverse map.
 
       
HashBiMap<String, String> map = HashBiMap.create();

        map.put("name", "Sohail");
        map.put("country", "Pakistan");

        Log.d("tag", "name is " + map.get("name"));
       
       
        BiMap<String, String>invmap= map.inverse();
       
        Log.d("tag", "Pakistan is a " + invmap.get("Pakistan"));


  

No comments:

Post a Comment