tags:

views:

73

answers:

3

I want to find out the key for given value from HashMap, currently I have to go through all keys and check its value in map, is there a faster way?

A: 

Use a better datastructure, like a TreeMap, as that will be much more efficient to search.

webdestroya
How is a `TreeMap` more efficient to search? You'd still need to walk through all values if you want to find the key for a given value.
Jesper
@Jesper - Yes, but because a treemap is sorted, the number of nodes you must traverse is generally (not always) much less than in a hashmap
webdestroya
@webdestroya a `TreeMap` is sorted by the *keys*, not the values, so if you want to find the key that matches a value, it doesn't help you that it's sorted by keys. You'll have to look at all the values.
Jesper
+3  A: 

No, there is not a faster way (without introducing other data structures). If you need to do this often, reconsider your design. Maybe you want another HashTable whose keys are the values of the other HashMap?

Justin Ardini
+5  A: 

An alternate data structure for doing this would be a BiMap from the google collections API.

The API doc is here.

spong