views:

37

answers:

2

So, this is probably a stupid question, but I have a mapping of unique IDs to unique values. Sometimes I want the value for a certain ID, sometimes I want to know the ID of a certain value. I search more than I modify the collection. I'm wondering if there's a special datastructure that makes sense here, or if I should just maintain two copies of the collection (which is never super large)--one keyed by ID, and one keyed by value.

Thanks!

+1  A: 

Something like Google's BiMap.

duffymo
Came here to post this. `BiMap<Integer, String> map = new HashBiMap<Integer,String>(); map.put(1,"Hello"); Integer id = map.inverse().get("Hello");`. But pretty much the implementation is actually 2 HashMaps maintained on each put().
Strelok
+1  A: 

Maintaining two copies of the collection is the canonical solution.

Note that the two directions can use different collection types if appropriate (e.g. hash tables with different hash functions, a hash table and a balanced tree, etc.).

Gilles