How to group map values by key in Java


A Java-map always contain a key and value (<key, value>). That key must always be unique so you can search your value by key. But what if you want to group values by key? Multimap, guava from Google gives you the solution.





public class MutliMapTest {
    public static void main(String... args) {
        Multimap<String, String> myMultimap = ArrayListMultimap.create();

        // Adding some key/value
        myMultimap.put("Fruits", "Banana");
        myMultimap.put("Fruits", "Apple");
        myMultimap.put("Fruits", "Pear");
        myMultimap.put("Vegetables", "Carrot");

        // Getting the size
        int size = myMultimap.size();
        System.out.println(size); // 4

        // Getting values
        Collection<String> fruits = myMultimap.get("Fruits")
        System.out.println(fruits); // [Banana, Apple, Pear]
        Collection<String> vegetables = myMultimap.get("Vegetables");
        System.out.println(vegetables); // [Carrot]

        // Iterating over entire Mutlimap
        for(String value : myMultimap.values()) {

        // Removing a single value
        System.out.println(myMultimap.get("Fruits")); // [Banana, Apple]

        // Remove all values for a key
        System.out.println(myMultimap.get("Fruits")); // [] (Empty Collection!)

When we just want the values from a key:

List<String> myValues = myMutlimap.get("myKey"); // Returns a List, not a Collection

Add comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud


%d bloggers like this: