Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 788
Yash Chitneni Avatar asked Dec 03 '25 09:12

Yash Chitneni


1 Answers

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.

like image 80
Andy Turner Avatar answered Dec 05 '25 22:12

Andy Turner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!