#35 - Simple bidirectional map

Data: 2018-11-17 12:00 - Java

A rough implementation for a bidirectional Map in Java for fast key and value lookups.

package bimap;

import java.util.HashMap;
import java.util.Map;

public class BiMap<K, V> {
    private Map<K, V> keyToValueMap = new HashMap<K, V>();
    private Map<V, K> valueToKeyMap = new HashMap<V, K>();

    synchronized public void put(K key, V value) {
    	keyToValueMap.put(key, value);
    	valueToKeyMap.put(value, key);
    }

    synchronized public V get(K key) {
    	return keyToValueMap.get(key);
    }

    synchronized public K getKey(V value) {
    	return valueToKeyMap.get(value);
    }

    synchronized public V remove(K key){
        V value = keyToValueMap.remove(key);
        valueToKeyMap.remove(value);
        return value;
    }

    synchronized public K removeKey(V value){
        K key = valueToKeyMap.remove(value);
        keyToValueMap.remove(key);
        return key;
    }

    public boolean containsKey(K key){
        return keyToValueMap.containsKey(key);
    }

    public boolean containsValue(V value){
        return valueToKeyMap.containsKey(value);
    }
}

Previous snippet | Next snippet