javacavaj javacavaj - 1 year ago 149
Java Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download