views:

1948

answers:

1

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 to do this?

Thanks in advance.

+10  A: 

The BiMap from Google Collections 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.

However, as sleske points out in the comments, BidiMap doesn't use generics. So if you're on Java 1.5 or later (which is likely, since 1.4 has reached end-of-life), you should probably prefer Google's BiMap.

Michael Myers
If you're on Java 1.5+, I'd recommend Google Collections, as Apache Common Collections do not use Java's generics.
sleske
Good point. I'll add that in.
Michael Myers
Excellent suggestions. Works perfectly!
javacavaj