Wednesday

Subtraction two maps by key using Guava library.


In Guava, we have a API work on Maps is difference, we use this API to implement the substraction operator.

Create a maven proj and add below dependency to pom.xml to use this library:
<dependency>
     <groupId>com.google.guava</groupId>
     <artifactId>guava</artifactId>
     <version>18.0</version>
</dependency>

Code:

import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.MapDifference;
import com.google.common.collect.Maps;

public class App {

    public static void main(final String[] args) throws IOException {
        final Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
        final Map<String, Integer> right = ImmutableMap.of("b", 2, "c", 4, "d", 5);
        final MapDifference<String, Integer> diff = Maps.difference(left, right);
        System.out.println("Common");
        mapToString(diff.entriesInCommon());
        System.out.println("Only Left");
        mapToString(diff.entriesOnlyOnLeft());
        System.out.println("Only Right");
        mapToString(diff.entriesOnlyOnRight());
    }

    private static void mapToString(final Map<String, Integer> map) {
        final Set<Entry<String, Integer>> entrySet = map.entrySet();
        for (final Entry<String, Integer> entry : entrySet) {
            System.out.println(entry.getKey() + "=>" + entry.getValue());
        }
    }
}


Output:
Common
b=>2
Only Left
a=>1
Only Right
d=>5