Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we have a MultiBiMap ?

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.

like image 1000
AR5HAM Avatar asked Dec 05 '13 03:12

AR5HAM


People also ask

Is there a multimap in Java?

A Multimap is a new collection type that is found in Google's Guava library for Java. A Multimap can store more than one value against a key. Both the keys and the values are stored in a collection, and considered to be alternates for Map<K, List<V>> or Map<K, Set<V>> (standard JDK Collections Framework).

What is a multimap used for?

A multimap can store more than one value against a key. Both keys and values are stored in the form of a tuple. A multimap is similar to a map in C+; the only difference is that a multimap can hold keys that are not unique (unlike in a standard map).

What is a multimap in CPP?

Multimap in C++ is an associative container that stores elements in sorted key-value pairs as a tuple. Multimap in C++ can store more than one value against a key. It is pretty similar to the map in C++, but the difference is that it can also contain duplicate keys that are not unique.

How is a multimap ordered?

Multimap is an associative container that contains a sorted list of key-value pairs, while permitting multiple entries with the same key. Sorting is done according to the comparison function Compare , applied to the keys. Search, insertion, and removal operations have logarithmic complexity.


1 Answers

import java.util.Set;

import com.google.common.collect.HashMultimap;
import com.google.common.collect.SetMultimap;

public class ManyToMany<K, V> {
    private final SetMultimap<K, V> keysToValues = HashMultimap.create();

    private final SetMultimap<V, K> valuesToKeys = HashMultimap.create();

    public Set<V> getValues(K key) {
        return keysToValues.get(key);
    }

    public Set<K> getKeys(V value) {
        return valuesToKeys.get(value);
    }

    public boolean put(K key, V value) {
        return keysToValues.put(key, value) && valuesToKeys.put(value, key);
    }

    public boolean putAll(K key, Iterable<? extends V> values) {
        boolean changed = false;
        for (V value : values) {
            changed |= put(key, value);
        }
        return changed;
    }
}
like image 130
gdejohn Avatar answered Oct 23 '22 12:10

gdejohn