Search code examples
data-structuresclojuredata-transform

Convert vector of strings into hash-map in Clojure


I have the following data structure:

["a 1" "b 2" "c 3"]

How can I transform that into a hash-map?

I want the following data structure:

{:a 1 :b 2 :c 3}


Solution

  • Use clojure.string/split and then use keyword and Integer/parseInt:

    (->> ["a 1" "b 2" "c 3"]
         (map #(clojure.string/split % #" "))
         (map (fn [[k v]] [(keyword k) (Integer/parseInt v)]))
         (into {}))
    => {:a 1, :b 2, :c 3}