在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'
我将使用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);
输出量
added [] removed [b] changed [c=333]