BiMap: A two-way Map in #android

Read Time < 1 minute
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 simplemap=new HashMap();
        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 map = HashBiMap.create();

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

        Log.d("tag", "name is " + map.get("name"));
      
      
        BiMapinvmap= map.inverse();
      
        Log.d("tag", "Pakistan is a " + invmap.get("Pakistan"));

  

Leave a Comment

Your email address will not be published. Required fields are marked *