Tuesday, January 06, 2009

BidiMap

This Map can be looked up by both the key and the value WITH the same performance. The catch is that the values should also be unique. Which is expected as the values become the keys in reverse lookup.

 

A simple example:

 

import org.apache.commons.collections.BidiMap;

import org.apache.commons.collections.bidimap.TreeBidiMap;

 

public class BidiMapDemo {

    public static void main(String[] args)

    {

        BidiMap map = new TreeBidiMap();

        map.put("US", "USA");

        map.put("IN", "India");

        map.put("UK", "United Kingdom");

       

        System.out.println(

            String.format(

                "Lookup by Key. key: %s Name: %s",

                "US",

                map.get("US") // returns "USA"

            )

        );

 

        System.out.println(

            String.format(

                "Lookup by value. Name: %s Key: %s",

                "India",

                map.getKey("India") // returns "IN"

            )

        );

       

    }

}

 

Output:

 

Lookup by Key. key: US Name: USA

Lookup by value. Name: India Key: IN

No comments: