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.
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 .
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.
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.
Java doesn't have a bidirectional map in its standard library.
Use for example BiMap<K, V>
from Google Guava .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With