How to compare two maps with different values using the Stream API? [closed]

Tags: ,



There are two maps and a method that accepts them and returns a new map. Maps contain the same number of the same keys, but their values ​​are different.

    Map<String, Boolean> a = new HashMap<>();
    Map<String, Boolean> b = new HashMap<>();

    a.put("a", false);
    a.put("b", true);
    a.put("c", true);

    b.put("a", true);
    b.put("b", true);
    b.put("c", false);

public static Map<String, Boolean> getNewMap(Map<String, Boolean> a, Map<String, Boolean> b) 
{
    Map<String, Boolean> newMap = new HashMap<>();
    for (Map.Entry<String, Boolean> mapB : b.entrySet())
        for (Map.Entry<String, Boolean> mapA : a.entrySet()) {
            if (mapB.getKey().equals(mapA.getKey()) && 
               !mapB.getValue().equals(mapA.getValue())) {
                newMap.put(mapB.getKey(), mapB.getValue());
            }
        }
    return newMap;
}

The method finds the same keys and writes the key and the different value of the second map to the new map

The result of the method will be a map with elements : “a” : true “c” : false

How can I reduce the amount of code by replacing loops and conditions with Stream API and lambda expressions?

Answer

If it’s OK to modify the original b, you don’t need a stream operation, EDIT: just use removeAll() (and if it isn’t OK, you may make a copy first).

    b.entrySet().removeAll(a.entrySet());
    System.out.println(b);

Output is what you said you wanted:

{a=true, c=false}

Thanks to Eritrean for suggesting removeAll rather than removeIf, an obvious improvement.

If you need to make a copy in order not to modify the original b, I suggest

    Map<String, Boolean> result = new HashMap<>(b);
    result.entrySet().removeAll(a.entrySet());


Source: stackoverflow