Difference between two maps

前端 未结 7 1488
悲&欢浪女
悲&欢浪女 2021-01-01 17:22

I need to very efficiently compare two maps in Clojure/Java, and return the difference as determined by Java\'s .equals(..), with nil/null equivalent to \"not present\".

相关标签:
7条回答
  • 2021-01-01 17:55

    Use the built-in collections API:

    Set<Map.Entry<K,V>> difference = a.entrySet().removeAll(b.entrySet());
    

    If you need to convert that back into a map, you must iterate. In that case, I suggest:

    Map<K,V> result = new HashMap<K,V>(Math.max(a.size()), b.size()));
    Set<Map.Entry<K,V>> filter = b.entrySet();
    for( Map.Entry<K,V> entry : a.entrySet ) {
        if( !filter.contains( entry ) {
            result.put(entry.getKey(), entry.getValue());
        }
    }
    
    0 讨论(0)
提交回复
热议问题