Skip to content

clojure.core/sorted-map-by

View this page on ClojureDocs

Type: function Added: Clojure 1.0 Examples: 4 Runnable: 2
([comparator & keyvals])

keyval => key val Returns a new sorted map with supplied mappings, using the supplied comparator. If any keys are equal, they are handled as if by repeated uses of assoc.

Examples

by gstamp on
by defiantt on . May have evaluation errors.
by aarkerio on
by ejschoen on . May have evaluation errors.

Note by noisesmith

an unstable sorting function will give nonsense results:

user=> (into (sorted-map-by (fn [_ _] (rand-int Integer/MAX_VALUE))) [[:a 0] [:a 1] [:a 2]])

{:a 0, :a 1, :a 2}

### Note by elias94

As previously noted, using an unstable sorting function could lead to unexpected results and hard to find bug. The `PersistentTreeMap` object returned by `sorted-map-by`, stores the `comparator` function and will reuse it in consecutive operations as `assoc`.

(def ord [:a :b :c])
(def m (into (sorted-map-by (fn [a b] 
                              (compare (.indexOf ord a) 
                                       (.indexOf ord b))))  
             {:a 1 :b 2 :c 3}))
(assoc m :d 4) ; => {:d 4, :a 1, :b 2, :c 3}
(-> (assoc m :d 4)
    (assoc :e 5)) ; => {:d 5, :a 1, :b 2, :c 3} WRONG
[Source reference](https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/PersistentTreeMap.java#L28) ## See also --- Content from [the matching ClojureDocs page](https://clojuredocs.org/clojure.core/sorted-map-by), with authors credited on each contribution.