Java compare two map
java
Solution
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]
Problem
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' ```