Get key ArrayListMultimap
I am using Guava collection ArrayListMultimap<K,V>
to display Integers
in Strings
. The class provides a method called containsValue(Object value)
that checks if the Multimap contains the specified value for any key. Once I determine that this is true, what's the best way to get the specified key?
ArrayListMultimap<String, Integer> myMap = ArrayListMultimap.create();
if (myMap.containsValue(new Integer(1))
{
// retrieve the key?
}
source to share
Instead, containsValue
you can iterate over myMap.entries () , which returns a collection of all key-value pairs. The iterator generated by the returned collection iterates over the values ββfor one key, then the values ββfor the second key, and so on:
Integer toFind = new Integer(1);
for (Map.Entry<String, Integer> entry: myMap.entries()) {
if (toFind.equals(entry.getValue())) {
// entry.getKey() is the first match
}
}
// handle not found case
If you look at the implementation containsValue
it just iterates over the map values ββin this way, the performance of doing it with map.entries()
instead map.values()
should be about the same.
public boolean containsValue(@Nullable Object value) {
for (Collection<V> collection : map.values()) {
if (collection.contains(value)) {
return true;
}
}
return false;
}
In general, of course, not necessarily a unique key for a given value, so unless you know that in your map each value only occurs against one key, you will need to specify the behavior, eg. if you want the first key or the last key.
source to share