Search code examples
javahashmapmultimapbimap

Do we have a MultiBiMap?


As we know, there is the concept of BiMap and MultiMap but is there a MultiBiMap ? so what do I mean by this. In MultiMap you have one-to-many relationship between K and V, a single key can be associated to multiple value, hence the name. In BiMap you have K,V pair which is bi-directional mean you can get V,K relationship as well. Like having a two regular maps but synchronized. I need a bi directional multi map where you combine these two concepts.


Solution

  • public class ManyToMany<K, V> {
        private final Map<K, Set<V>> values = new HashMap<>();
    
        private final Map<V, Set<K>> keys = new HashMap<>();
    
        public Set<V> getValues(K key) {
            return values.get(key);
        }
    
        public Set<K> getKeys(V value) {
            return keys.get(value);
        }
    
        public boolean put(K key, V value) {
            return values.computeIfAbsent(key, k -> new HashSet<>()).add(value)
                && keys.computeIfAbsent(value, v -> new HashSet<>()).add(key);
        }
    }