Search code examples
javakeyguavamultimap

Return key from value in Guava Multimap


In my Java code, I need to be able to figure out the key from a value. I know how to do it vice versa, and I have used that many times in my code, but is there a way I could get the key while only knowing the value in Guava Multimap? Thanks in advance.


Solution

  • Guava supplies an inversion method for Multimap. See Multimaps.invertFrom.

    This might do fine for you if you don't frequently need the inversion, or if your multimap is small. But this inversion is an expensive process. You can likely gain some efficiency by simply maintaining both forward and reverse as suggested by JB Nizet in comments. Both however can be multimaps to allow for non-uniqueness.