I need a collection that can lookup a value based on the key and vice versa. For every value there is one key and for every key there is one value. Is there a ready to use data structure out there that does this?
HashMap is a collection to store (key,value) pairs and According to the documentation of HashMap the keys are always unique. If you add a key which already exists(collision) in the hashmap, the old value will be replaced.
HashMap is used to store key-value pairs using put method Example: hm. put(key, value); while HashSet is used to store only unique objects using add method Example: hs. add(object);. HashSet internally uses HashMap.
You could just use a HashSet<String> to maintain a collection of unique objects.
Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. Parameter: This method does not take any parameter.
The BiMap from Google Guava looks like it will suit you.
A bimap (or "bidirectional map") is a map that preserves the uniqueness of its values as well as that of its keys. This constraint enables bimaps to support an "inverse view", which is another bimap containing the same entries as this bimap but with reversed keys and values.
Or the BidiMap from Apache Commons Collections:
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 extendsMap
and so may be used anywhere a map is required. The interface provides an inverse map view, enabling full access to both directions of theBidiMap
.
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