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
2010-05-14 02:12:39
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
2010-05-14 08:20:59
@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
2010-05-14 19:10:36
@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
2010-05-14 21:53:16
+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
2010-05-14 02:13:48