I'm using Hashmap to access the value based on its corresponding key. But it seems the hashMap is a one-way mapping.
Here's my sample code:
If I want to get the value, I use this:
But is there a way to get the key given only the value?
I know there are other methods other than using HashMap. But I want something fast. The database would contain >1K of pairs. I could only think that the only way would be to create another hashMap, but with the arguments swapped.
[Karen]: I could only think that the only way would be to create another hashMap, but with the arguments swapped.
Yes, if you want something that's reasonably fast, that's basically what you have to do. You could also write a containing class which ensures that whenever you add a mapping, the inverse mapping is added to the second hashmap. So you can make sure the two maps don't get out of sync. Infact this work has already been done for you, if you check out the DualHashBidiMap in Jakarta Commons. There are several other implemenations of bidirectional ("bidi") maps available there.