Search code examples
javaguavarelationmultimap

Swapping relation of keys and values in a Google Guava Multimap


I have a

Multimap<String, Integer> map = ...

where I can do map.get("somekey") to retrieve all the matching Integers.

Now I would like to find the keys that have a given Integer, i.e. something like a

Collection<String> keys = map.getByValue(Integer.of(4))

which returns all keys in the Multimap where the given Integer is stored as value.

Is there an easy way to do this in Google Guava?


Solution

  • Shortly after posting the question I found the following which does the Job nicely:

    Multimap<String, Integer> reversed = ...
    Multimaps.invertFrom(map, reversed);
    

    It will actually do a copy, a solution that does this without actually copying all the entries would still be interesting.