Clojure: working with a java.util.HashMap in an idiomatic Clojure fashion

后端 未结 4 1490
醉酒成梦
醉酒成梦 2020-12-14 07:12

I have a java.util.HashMap object m (a return value from a call to Java code) and I\'d like to get a new map with an additional key-value pair.

4条回答
  •  旧时难觅i
    2020-12-14 07:48

    Clojure makes the java Collections seq-able, so you can directly use the Clojure sequence functions on the java.util.HashMap.

    But assoc expects a clojure.lang.Associative so you'll have to first convert the java.util.HashMap to that:

    (assoc (zipmap (.keySet m) (.values m)) "key" "value")
    

    Edit: simpler solution:

    (assoc (into {} m) "key" "value")
    

提交回复
热议问题