Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java compare two map

Tags:

java

In java, I want to compare two maps, like below, do we have existing API to do this ?

Thanks

Map<String, String> beforeMap ;
beforeMap.put("a", "1");
beforeMap.put("b", "2");
beforeMap.put("c", "3");

Map<String, String> afterMap ;
afterMap.put("a", "1");
afterMap.put("c", "333");

//--- it should give me:
b is missing, c value changed from '3' to '333'
like image 526
user595234 Avatar asked May 14 '12 16:05

user595234


People also ask

How do I compare two map keys and values in Java?

The way that Map. equals() works is by comparing keys and values using the Object. equals() method. This means it only works when both key and value objects implement equals() properly.

How do you check a map is equal or not in Java?

util. Map. equals() method in Java is used to check for equality between two maps. It verifies whether the elements of one map passed as a parameter is equal to the elements of this map or not.


1 Answers

I'd use removeAll() functionality of Set to to do set differences of keys to find additions and deletions. Actual changes can be detected by doing a set difference using the entry set as HashMap.Entry implements equals() using both key and value.

Set<String> removedKeys = new HashSet<String>(beforeMap.keySet());
removedKeys.removeAll(afterMap.keySet());

Set<String> addedKeys = new HashSet<String>(afterMap.keySet());
addedKeys.removeAll(beforeMap.keySet());

Set<Entry<String, String>> changedEntries = new HashSet<Entry<String, String>>(
        afterMap.entrySet());
changedEntries.removeAll(beforeMap.entrySet());

System.out.println("added " + addedKeys);
System.out.println("removed " + removedKeys);
System.out.println("changed " + changedEntries);

Output

added []
removed [b]
changed [c=333]
like image 76
Adam Avatar answered Nov 06 '22 16:11

Adam