Search code examples
sortingdictionaryclojuresortedmap

If I call keys on a sorted-map, is the resulting seq guaranteed to be in sorted order?


If I were to call keys on a sorted-map type, I would assume the resulting seq would be in the same order as the key-value pairs in the map.

However, a user from ClojureDocs named Jarzka had this to say about 2 years ago:

I noticed that the keys are not always returned in the same order. Usually they are, but not always.

(Unfortunately I can't directly link to the comment. It's at the bottom of the page describing keys.)

Why might this be? Should I (sort (keys m)) just to be safe?

(def m (sorted-map :a 1, :b 2, :c 3))

(def maybe-unsorted-keys? (keys m))
(def sorted-keys (sort (keys m))) 

Solution

  • If you look at the implementation of keys and vals, it looks like a valid assumption that they will be returned in the same order, sorted:

    https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentTreeMap.java#L888