Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bidirectional Map

Can you suggest a kind of map or similar data structure where we can get both the value and key from each other at equal ease. That is to say, that each may be used to find other.

like image 800
mawia Avatar asked Mar 20 '12 07:03

mawia


People also ask

What is bidirectional mapping?

In computer science, a bidirectional map is an associative data structure in which the pairs form a one-to-one correspondence. Thus the binary relation is functional in each direction: each can also be mapped to a unique .

What BiMap?

A BiMap (or “bidirectional map”) is a special kind of a map that maintains an inverse view of the map while ensuring that no duplicate values are present and a value can always be used safely to get the key back.

What is BidiMap?

public interface BidiMap<K,V> extends IterableMap<K,V> Defines a map that allows bidirectional lookup between key and values. This extended Map represents a mapping where a key may lookup a value and a value may lookup a key with equal ease. This interface extends Map and so may be used anywhere a map is required.


Video Answer


3 Answers

Java doesn't have a bidirectional map in its standard library.

Use for example BiMap<K, V> from Google Guava .

like image 153
Jesper Avatar answered Oct 18 '22 20:10

Jesper


If you feel it pain importing some third party library. How about this simple class.

public class BiMap<K,V> {

    HashMap<K,V> map = new HashMap<K, V>();
    HashMap<V,K> inversedMap = new HashMap<V, K>();

    void put(K k, V v) {
        map.put(k, v);
        inversedMap.put(v, k);
    }

    V get(K k) {
        return map.get(k);
    }

    K getKey(V v) {
        return inversedMap.get(v);
    }

}

Make sure K and V class has proper hashCode implementation.

like image 36
Rohit Sharma Avatar answered Oct 18 '22 20:10

Rohit Sharma


The most common solution is using two maps. You can easily encapsulate them in a class with a friendly interface by extending AbstractMap. (Update: This is how Guava's HashBiMap is implemented: two maps)

Creating a new data structure using nothing but arrays and custom classes has few advantages. The map implementations are lightweight wrappers of a data structure that indexes the keys. Since you need two indexes you might as well use two complete maps.

like image 14
Joni Avatar answered Oct 18 '22 20:10

Joni