Bi-directional Map in Java? [duplicate] Bi-directional Map in Java? [duplicate] java java

Bi-directional Map in Java? [duplicate]


You can use the Google Collections API for that, recently renamed to Guava, specifically a BiMap

A bimap (or "bidirectional map") is a map that preserves theuniqueness of its values as well as that of its keys. This constraintenables bimaps to support an "inverse view", which is another bimapcontaining the same entries as this bimap but with reversed keys andvalues.


Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;import com.google.common.collect.HashBiMap;public class BiMapTest {  public static void main(String[] args) {    BiMap<String, String> biMap = HashBiMap.create();    biMap.put("k1", "v1");    biMap.put("k2", "v2");    System.out.println("k1 = " + biMap.get("k1"));    System.out.println("v2 = " + biMap.inverse().get("v2"));  }}


There is no bidirectional map in the Java Standard API. Either you can maintain two maps yourself or use the BidiMap from Apache Collections.