I need a data structure to store string-int value pairs in an 1:1 relationship, and being able too look up from either way their counterpart.
I wrote a class with a Hashtable and a String array and stored the data 2 times and used the built in functions for lookup.
My question is that is there a nicer way to accomplish this? And by nicer I mean being efficient and not storing the data 2 times, and preferably without writing a ton of code either :P.
It seems like you may be looking for a bimap.
The Google Collections (now a part of Guava) contains an
BiMapinterface with a few implementations.From the
BiMapdocumentation:The
BiMap.inversemethod appears to return aMapwith the values as the keys, and the keys as the values, so thatMapcan be used to callgeton the value and retrieve a key.In addition the
Mapreturned byinverseis a view of the underlying data, so it does not have to make extra copies of the original data.From the
BiMap.inversemethod documentation: