Search code examples
javaguavamultimap

Multimap how to return all values from a key


Multimaps can have multiple values how would I be able to return all the values from a key if it contains multiple values.

Multimap<String, String> wordcount = ArrayListMultimap.create();

wordcount.put("1", "Dog");
wordcount.put("1", "Dog2");
wordcount.put("1", "Dog3");

So you can see above I gave my Multimap key "1" the following values "Dog", "Dog2" & "Dog3" how would I be able to print out all the dogs?

Extra Questions How would I be able to check if a key contains multiple values of the same string for that specific key? Also how would I be able to return the amount of "same" strings it contains. It should return 3 because I specified the value 3 times with the same value so it should return 3.

wordcount.put("1", "Dog");
wordcount.put("1", "Dog");
wordcount.put("1", "Dog");

Solution

  • You can just do wordcount.get("1") it will return a List containing Dog1, Dog2, Dog3

    For your extra question: I think you have to do wordcount.get("1") to get the List object and iterate through the list object if you want to use an ArrayListMultimap instance.

    Alternatively, you may want to checkout Multiset<String> that keeps track of number of occurrences of your input Strings. In this case you can use Map<String, Multiset<String>> instead of ArrayListMultimap instance to avoid iterating the returned list.

    But Multiset<?> is a set so it does not iterate in the order you put the values.