Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Collection - Unique Key and Unique Value

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?

like image 343
javacavaj Avatar asked Apr 02 '09 21:04

javacavaj


People also ask

Is key unique in HashMap?

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.

How do I store unique values on a map?

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.

Which type of collection accepts only unique values?

You could just use a HashSet<String> to maintain a collection of unique objects.

What is the return type of values () method in map?

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.


1 Answers

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 extends Map and so may be used anywhere a map is required. The interface provides an inverse map view, enabling full access to both directions of the BidiMap.

like image 184
Michael Myers Avatar answered Sep 18 '22 05:09

Michael Myers