BidiMap Example

Apache Common Collections framework provide a new map collection called “BidiMap”. This collection is similar to map and at the same time it is different.

1) Both will contain list of entries each of key value pair
2) By using key we can retrieve the corresponding value

1) In BidiMap we can invert the existing map, meaning as part of invert, the key becomes the value, and the value becomes key.
2) In java Map, the value can be duplicated but in BidiMap the value has to be unique. The unqiueness of the value helps in inverting the map.

The BidiMap extends Java util map and inherit its methods.

Below is the example of BidiMap


1  import org.apache.commons.collections4.BidiMap;
2  import org.apache.commons.collections4.bidimap.DualHashBidiMap;
4  public class Example2 {
5   public static void main(String[] args) {
6       BidiMap bidiMap1 = new DualHashBidiMap();
7       bidiMap1.put(1, "A");
8       bidiMap1.put(2, "B");
9       bidiMap1.put(3, "C");
10      System.out.println(bidiMap1);
11      System.out.println(bidiMap1.getKey("B"));
12      bidiMap1.removeValue("C");
13      System.out.println(bidiMap1);
15      BidiMap bidiMap2 = bidiMap1.inverseBidiMap();
16      System.out.println(bidiMap2);
17      System.out.println(bidiMap2.getKey(2));
18  }
19 }


At line 6, we create an instance of BidiMap. At line 7 to 9, we insert key 1, 2, and 3 and corresponding values A, B, and C. Note that the keys and values are both unique.

At line 10 we print the contents of BidiMap.

At line 11, we print the key for value B using getKey method.

At line 12, we remove the value Collections

At line 13, we again print the value of BidiMap.

At line 15, we create a inverted version of map bidiMap1 and assign it to bidiMap2. In bidiMap2, the key in bidiMap1 becomes the value and the value in bidiMap1 becomes the key.

At line 16, we print the contents of bidiMap2.


{1=A, 2=B, 3=C}
{1=A, 2=B}
{A=1, B=2}

Leave a Reply