How to group map values by key in Java

H

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.

Maven:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>14.0</version>
</dependency>

Jar:

http://mvnrepository.com/artifact/com.google.guava/guava/14.0

Code:

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()) {
            System.out.println(value);
        }

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

        // Remove all values for a key
        myMultimap.removeAll("Fruits");
        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

Categories