4

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.

cataschok
  • 339
  • 1
  • 6
  • 10

3 Answers3

4

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.

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
2

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).

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

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
        }
    }
}
Jerome
  • 4,472
  • 4
  • 18
  • 18