Does Java have a HashMap with reverse lookup? Does Java have a HashMap with reverse lookup? java java

Does Java have a HashMap with reverse lookup?


There is no such class in the Java API. The Apache Commons class you want is going to be one of the implementations of BidiMap.

As a mathematician, I would call this kind of structure a bijection.


Here is a simple class I used to get this done (I did not want to have yet another third party dependency). It does not offer all features available in Maps but it is a good start.

    public class BidirectionalMap<KeyType, ValueType>{        private Map<KeyType, ValueType> keyToValueMap = new ConcurrentHashMap<KeyType, ValueType>();        private Map<ValueType, KeyType> valueToKeyMap = new ConcurrentHashMap<ValueType, KeyType>();        synchronized public void put(KeyType key, ValueType value){            keyToValueMap.put(key, value);            valueToKeyMap.put(value, key);        }        synchronized public ValueType removeByKey(KeyType key){            ValueType removedValue = keyToValueMap.remove(key);            valueToKeyMap.remove(removedValue);            return removedValue;        }        synchronized public KeyType removeByValue(ValueType value){            KeyType removedKey = valueToKeyMap.remove(value);            keyToValueMap.remove(removedKey);            return removedKey;        }        public boolean containsKey(KeyType key){            return keyToValueMap.containsKey(key);        }        public boolean containsValue(ValueType value){            return keyToValueMap.containsValue(value);        }        public KeyType getKey(ValueType value){            return valueToKeyMap.get(value);        }        public ValueType get(KeyType key){            return keyToValueMap.get(key);        }    }