How to print the matching value of key from (Google Guava) Multimap?

42 Views Asked by At

I would like to print the matching value of key from multimap. So far I have been unsuccessful at it.

These are the line of code I got so far about it :

 dictionaryGG.keys().forEach((key) -> {
            if (userInput.equals(key)) {
                System.out.println("User Input equal to KEY");
                System.out.println("Value associated with matching KEY" + value); // get an error here "value cannot be resolved to a variable"
            }
            System.out.println(key);
        }); ```

(dictionaryGG is my multimap)
1

There are 1 best solutions below

0
Grzegorz Rożniecki On

Please read the Guava Wiki page on Multimap:

There are two ways to think of a Multimap conceptually: as a collection of mappings from single keys to single values:

a -> 1
a -> 2
a -> 4
b -> 3
c -> 5

or as a mapping from unique keys to collections of values:

a -> [1, 2, 4]
b -> [3]
c -> [5]

That said, you can fetch values mapped to a multimap key by simply using Multimap#get(K):

Collection<String> values = dictionaryGG.get(userInput);
System.out.println("Values: " + values); // assuming you store strings

Please note that if you don't expect to have multiple values per key, a simple Map & Map#get(Object) is sufficient.