zipmap creates a map by pairing corresponding elements from separate collections of keys and values. It is especially useful when those collections emerge from processing, such as parsed records or CSV rows. section 11.1.5
Its contract is straightforward:
- Accepts two sequential collections, keys and vals; either may be nil or empty. section 11.1.5
- Pairs elements in order and stops when the shorter collection is exhausted. section 11.1.5
- Returns an empty map when either input is nil or empty, and throws IllegalArgumentException for non-sequential inputs. section 11.1.5
- Lets later occurrences of duplicate keys overwrite earlier values, following assoc semantics. section 11.1.5
- May return a PersistentArrayMap or PersistentHashMap; map printing and iteration need not preserve input order. section 11.1.5
Pairing collections
(zipmap [:a :b :c] [1 2 3]) ;; {:a 1, :b 2, :c 3} (zipmap ["red" "blue" "green"] (repeat 1)) ;; {"red" 1, "blue" 1, "green" 1} section 11.1.5
(require '[clojure.java.io :as io])
(require '[clojure.string :as s])
(def file-content ; #1
"TITLE,FIRST,LAST,NUMBER,STREET,CITY,POST,JOINED
Mrs,Mary,Black,20,Hillbank St,Kelso,TD5 7JW,01/05/2012 12:51
Miss,Chris,Bowie,44,Hall Rd,Sheffield,S5 7PW,01/05/2012 17:02
Mr,John,Burton,41,Warren Rd,Yarmouth,NR31 9AB,01/05/2012 17:08")
(defn split-line [line] ; #2
(s/split line #","))
(defn transform [data] ; #3
(let [lines (line-seq data)
headers (split (first lines))]
(eduction
(map split)
(map (partial zipmap headers)) ; #4
(rest lines))))
(with-open [data (io/reader (char-array file-content))] ; #5
(doall (transform data)))
;; ({"TITLE" "Mrs", "FIRST" "Mary", "LAST" "Black", "NUMBER" "20",
;; "STREET" "Hillbank St", "CITY" "Kelso", "POST" "TD5 7JW",
;; "JOINED" "01/05/2012 12:51"}
;; {"TITLE" "Miss", "FIRST" "Chris", "LAST" "Bowie", "NUMBER" "44",
;; "STREET" "Hall Rd", "CITY" "Sheffield", "POST" "S5 7PW",
;; "JOINED" "01/05/2012 17:02"}
;; {"TITLE" "Mr", "FIRST" "John", "LAST" "Burton", "NUMBER" "41",
;; "STREET" "Warren Rd", "CITY" "Yarmouth", "POST" "NR31 9AB",
;; "JOINED" "01/05/2012 17:08"})
Follow the CSV transformation to see zipmap turn header names and row values into one map per record. section 11.1.5
Composing processed keys and values
After parsing and formatting an XML balance, separate transformations produce keys and values; zipmap combines them without requiring reduce or assoc. section 1.5
