Difference between two maps

前端 未结 7 1520
悲&欢浪女
悲&欢浪女 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:45

    I am not sure about its performance

    (defn map-difference
      [orig other]
      (let [changed (set/difference (set orig) (set other))
            added (set/difference (set (keys other)) (set (keys orig)))]
        (reduce (fn [acc key]
                  (assoc acc key :missing))
          (into {} changed)
          added)))
    

    I used :missing key to avoid ambiguity between a nil value in the original map, and a missing key -- you can of course change it to nil.

提交回复
热议问题