Issue
As we now, 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 bi map 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);
}
}
Answered By - gdejohn
Answer Checked By - Marilyn (JavaFixing Volunteer)