How to output unique keys with MultiMap from Guava? (Java)

1.8k views Asked by At

I've got the following method:

public static void showStuff(Multimap<String, String> map) {
        for (String key : map.keys()) {
            System.out.println("The key, " + key
                    + ", has the results: " + map.get(key));
        }
    }

This outputs:

The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **one**, has the results: [a,b,c,d,d,e]
The key, **two**, has the results: [a,a,a,b,b,e]
The key, **two**, has the results: [a,a,a,b,b,e]

How would I have it only output unique keys. I want it to only printout the statement once rather than repeat it multiple times. I have a table with different rows with duplicate keys, hence I used the MultiMap to get all the values for a duplicated key. How will I now output only

The key, **one**, has the results: [a,b,c,d,d,e]
The key, **two**, has the results: [a,a,a,b,b,e]

Thank You!

2

There are 2 answers

0
Andy Turner On BEST ANSWER

You can use Multimap.keySet() to get just the distinct keys.

You can use Multimap.entries() to get the (key, values) pairs, rather than having to go back to the map to request the values associated with each key.

Alternatively, you can use Multimap.asMap() to convert it to a java.util.Map, and then work with that instead.

0
Raman Shrivastava On

Use map.keySet() instead of map.keys()