AR5HAM
AR5HAM

Reputation: 1304

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.

Upvotes: 8

Views: 4141

Answers (1)

gdejohn
gdejohn

Reputation: 7589

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);
    }
}

Upvotes: 16

Related Questions