In a linked hashmap Is there any methods to get the value of K by only providing V? I've searched all over the internet and so far I've only found loops to get the key.
-
I think you have no other way except for loop – Mike Lin Mar 02 '12 at 04:26
-
4http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value Has the answers your looking for. – Dan675 Mar 02 '12 at 04:26
-
value cant be unique...so there is a possibility to get multiple keys for the same value..... – Shashank Kadne Mar 02 '12 at 04:27
3 Answers
No.
The point of a Map is to associate the V with a specific K, not the other way around. You would have to go through every K/V pair linearly (your loop).
If this is something that would be a common operation, you'd want to create a second map that went the other way (and probably wrap both in a class that abstracted that away). Of course the tricky bit is if you're not talking about unique values.

- 76,169
- 12
- 136
- 161
There isn't anything that's better than a loop with a vanilla LinkedHashMap
, but here are some alternatives with Guava...
If you know your values are unique, the BiMap
API supports inverse lookups efficiently without having to maintain a backwards map by hand. Use HashBiMap
as your implementation, and you can look up a key from a value with bimap.inverse().get(value)
.
If your values aren't unique, you could potentially build a Multimap
that maps each value to each of its associated keys. You could do this quickly using
Multimap<V, K> reverse = Multimaps.invertFrom(
Multimaps.forMap(map),
HashMultimap.<V, K> create());
which would let you look up all the keys associated with a value by using reverse.get(value)
.

- 191,574
- 25
- 345
- 413
A Map is not intended to be used this way, see @Brian Roach 's answer. You should consider replacing that Map by something else or consider reversing its key / values.
Anyway, you can find the keys corresponding to valueToFind have this way:
if (map.containsValue(valueToFind)) {
for (final Object /* whatever you use, your 'K' type */ entry : map.keySet()) {
if (map.get(entry) == valueToFind) {
//You found one key containing valueToFind
//Keep searching, there may be others
}
}
}

- 4,472
- 4
- 18
- 18