1

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.

Connor M
  • 331
  • 3
  • 5
  • 18
  • 3
    A BiMap is what you want. Not a Multimap. – JB Nizet Dec 21 '13 at 15:42
  • Oh, ok thanks, I'm still new to Guava. But would the BiMap be able to have more than one value per key? – Connor M Dec 21 '13 at 15:43
  • 2
    No. In that case, you should probably use a Multimap (for key -> values), and another Map (for value -> key, assuming a given value is only associated with one key). – JB Nizet Dec 21 '13 at 15:46
  • 1
    [Relevant Guava issue](http://code.google.com/p/guava-libraries/issues/detail?id=394) (feature request for Many to Many relationship-based map) and [similar question](http://stackoverflow.com/questions/5578029/what-is-the-best-guava-google-collection-api-to-represent-direct-or-inverse-re) plus [another answer linking to thread anout `BiMultimap`](http://stackoverflow.com/a/7912387/708434). Long story short - `BiMultimap` is used internally in Google but it's not open-sourced (yet). – Grzegorz Rożniecki Dec 22 '13 at 17:07

3 Answers3

3

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.

user2591854
  • 182
  • 3
  • 15
Don Roby
  • 40,677
  • 6
  • 91
  • 113
1

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

Jared Levy
  • 1,986
  • 13
  • 12
0

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.

xiaoyifang
  • 919
  • 12
  • 13