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.

asked Mar 2, 2012 at 4:22
3
  • I think you have no other way except for loop Commented Mar 2, 2012 at 4:26
  • 4
    stackoverflow.com/questions/1383797/… Has the answers your looking for. Commented Mar 2, 2012 at 4:26
  • value cant be unique...so there is a possibility to get multiple keys for the same value..... Commented Mar 2, 2012 at 4:27

3 Answers 3

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.

answered Mar 2, 2012 at 4:31
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).

answered Mar 2, 2012 at 4:57
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
 }
 }
}
answered Mar 2, 2012 at 4:49

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.