在java中,我想比较两个地图,如下所示,我们是否有现有的API来执行此操作?
谢谢
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'
Run Code Online (Sandbox Code Playgroud)
Ada*_*dam 29
我将使用Set的removeAll()功能来设置键的差异以查找添加和删除.可以通过使用条目集HashMap进行设置差异来检测实际更改.Entry使用键和值实现equals().
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);
Run Code Online (Sandbox Code Playgroud)
产量
added []
removed [b]
changed [c=333]
Run Code Online (Sandbox Code Playgroud)