Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the different values in 2 HashMaps

Tags:

java

hashmap

I have 2 HashMaps with millions of records. For simplicity, I will deal with only few records. I want to find the values which are in map a that are not in map b. Is there a function to do this? What's the quickest way to go about it?

Map a = new HashMap();
a.put(1, "big");
a.put(2, "hello");
a.put(3, "world");

Map b = new HashMap();

b.put(1,"hello");
b.put(2, "world");

In this case, output should be "big" since it is in a and not in b.

like image 792
Jany Gwan Avatar asked Dec 06 '22 19:12

Jany Gwan


2 Answers

You are looking for the removeAll operation on the values of the map.

public static void main(String[] args) {
    Map<Integer, String> a = new HashMap<>();
    a.put(1, "big");
    a.put(2, "hello");
    a.put(3, "world");

    Map<Integer, String> b = new HashMap<>();
    b.put(1,"hello");
    b.put(2, "world");

    a.values().removeAll(b.values()); // removes all the entries of a that are in b

    System.out.println(a); // prints "{1=big}"
}

values() returns a view of the values contained in this map:

Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.

So removing elements from the values effectively removes the entries. This is also documented:

The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations.


This removes from the map in-place. If you want to have a new map with the result, you should call that method on a new map instance.

Map<Integer, String> newMap = new HashMap<>(a);
newMap.values().removeAll(b.values());

Side-note: don't use raw types!

like image 75
Tunaki Avatar answered Dec 24 '22 11:12

Tunaki


The solution of @Tunaki will work fine, is readable and short.

Just for the sake of completeness the solution "by hand":

for (String s : a.values()) {
    if (!b.containsValue(s)) {
        System.out.println (s);
        // process the value (e.g. add it to a list for further processing)
    }
}
like image 42
ParkerHalo Avatar answered Dec 24 '22 09:12

ParkerHalo