Frage

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.

War es hilfreich?

Lösung

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.

Andere Tipps

With an ImmutableMultimap, you can call ImmutableMultimap.inverse().

use BiMap, https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/BiMap.html

then,

bimap.inverse().get(value)

will give you the key.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top