Search code examples
vectorclojurekey-valuedestructuring

Destructure and process vector of hash-maps in Clojure


I have a vector of hash-maps, like this:

(def my-maps [{:a 1} {:b 2}])

I want to loop over each hash-map, give the key and value a more meaningful name within the loop, then process each hash-map differently depending on its key.

Without further ado, here is my best attempt:

(for [m my-maps]
  (let [my-key-name (key m) my-val-name (val m)]
    (case my-key-name
      :a (println "Found key :a with value " my-val-name)
      :b (println "Found key :b with value " my-val-name))))

This approach, however, produces a rather cryptic error:

; Error printing return value (ClassCastException) at clojure.core/key (core.clj:1569).
; class clojure.lang.PersistentArrayMap cannot be cast to class java.util.Map$Entry (clojure.lang.PersistentArrayMap is in unnamed module of loader 'app'; java.util.Map$Entry is in module java.base of loader 'bootstrap')

What am I doing wrong?


Solution

  • You can destructure inside for (or use doseq):

    (for [[[k v] & _] [{:a 1} {:b 2}]]
      (println "Found key" k "with value" v))
    
    Found key :a with value 1
    Found key :b with value 2
    => (nil nil)