A related hashmap defining a key by value?

In a related hashmap Are there any methods to get the value of K, only providing V? I searched all over the Internet, and so far I only found cycles to get the key.

+4
source share
3 answers

Not.

The map point is a mapping of V to a specific K, and not vice versa. You will have to go through each K / V pair linearly (your loop).

If this is what would be a normal operation, you would want to create a second card that went the other way (and possibly wrap both classes that distracted them). Of course, a difficult bit is if you are not talking about unique values.

+4
source

The map is not intended to be used this way, see @Brian Roach's answer. You should consider replacing this Card with something else or consider changing its key / values.

In any case, you can find the keys corresponding to the ValueToFind value as follows:

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 } } } 
+1
source

There's nothing better than a LinkedHashMap vanilla LinkedHashMap , but here are a few alternatives with Guava ..

If you know that your values ​​are unique, the BiMap API supports reverse lookups efficiently, without having to manually support reverse lookups. Use HashBiMap as your implementation, and you can search for a key from a value using bimap.inverse().get(value) .

If your values ​​are not unique, you can create a Multimap that displays each value for each of the associated keys. You can do it fast using

 Multimap<V, K> reverse = Multimaps.invertFrom( Multimaps.forMap(map), HashMultimap.<V, K> create()); 

which allows you to view all keys associated with a value using reverse.get(value) .

+1
source

Source: https://habr.com/ru/post/1399310/


All Articles