Pure Danger Tech


Learning Clojure #3: Sorted Maps

09 Feb 2010

This is a quick one. I had a map in Clojure and I needed a sorted version of it.

Most commonly I’ve created maps in Clojure using the literal syntax: { <key1> <val1> <key2> <val2> }.

There are also functions hash-map and sorted-map available. If you want, you can make the analogy to HashMap and TreeMap if you are Java minded although note they are NOT HM or TM. Instead these are Clojure “persistent” data structures that are an intrinsic part of the language.

Back to the problem at hand… I had a map and I needed a sorted-map. You can do this as follows:

; dummy existing map
(def existingMap {:dog 1 :cat 2})

; created sorted version
(into (sorted-map) existingMap)

No biggie but it took me a few minutes to figure it out. This just creates a sorted-map structure then uses into to add all of the existingMap data into it.

You might be tempted to use the sort function instead. Don’t! Calling sort on a map yields a sorted sequence of vectors of each key-value pair and not a map. This is due to how sort works on the sequence view of the map.

user=> (sort { :dog :bark :cat :meow :mime nil })
([:cat :meow] [:dog :bark] [:mime nil])