簡體   English   中英

找出兩張地圖之間的差異

[英]Find the differences between two maps

我有兩張當前和之前的地圖,我想看看兩張地圖之間是否有任何差異。 如果currentMap中存在新鍵,或者同一個鍵的值不同,我可以停止。

Map<String, String> previousValue;
Map<String, String> currValue;

boolean isChangePresent = currValue.entrySet().stream().anyMatch(
                    x -> !previousValue.containsKey(x.getKey()) ||
                        (previousValue.get(x.getKey()) != null && !previousValue.get(x.getKey()).equals(
                            x.getValue())));

有沒有更好的方法來做這個或內置的實用功能,這樣做的東西?

在番石榴:

MapDifference<String, String> mapDifference = Maps.difference(currValue, previousValue);

return !mapDifference.entriesOnlyOnLeft().isEmpty() 
        || !mapDifference.entriesDiffering().isEmpty();

https://www.leveluplunch.com/java/examples/guava-map-difference-example/

由於你的鍵和值只是Strings ,它們的.equals()方法檢查邏輯相等(而不是檢查它們是否有相同的內存地址),所以你可以簡單地使用

boolean check(Map<String, String> a, Map<String, String> b) {
     return a.equals(b);
}

請注意,例如,如果您有兩個Map<K,V>類型的Map<K,V>其中V沒有重寫的.equals()方法,並且V的默認equals方法不檢查邏輯相等,那么它將不行。

編輯:

更仔細地看一下你的措辭,如果previousMapkeySet包含currentMap所有鍵但是 currentMappreviousMap少了鍵,你會考慮改變嗎? 如果你認為沒有變化那么你需要做的是

boolean check(Map<String, String> previous, Map<String, String> current) {
         Map<String,String> copyOfPrev = new HashMap<>();
         previous.forEach((k,v) -> copyOfPrev.put(k,v));
         copyofPrev.keySet().retainAll(current.keySet());
         return copyOfPrev.equals(current);
    }

請記住Map<K, V>#keySet().retainAll(Collection<K> c)修改基礎地圖,因此深層復制是為了防止更改上一個地圖。 如果您可以更改上一個地圖,那么您可以刪除該方法正文的前三行,並將copyOfPrev更改為previous

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM