You're viewing version 1.2.0 of sorted-map-by. The latest stable version of Clojure Core is 1.3.0.
1.2.0 Arrow_down_16x16

sorted-map-by

clojure.core

  • (sorted-map-by comparator & keyvals)
keyval => key val
Returns a new sorted map with supplied mappings, using the supplied comparator.

2 Examples top

  • user> (sorted-map-by > 1 "a", 2 "b", 3 "c")
    {3 "c", 2 "b", 1 "a"}
  • ;; If you wish to sort the map according to the values, instead of by keys 
    ;; the following code WILL NOT WORK! This is because the map values are not unique.
    
    user=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]
      (into (sorted-map-by (fn [key1 key2]
                             (compare (get results key2)
                                      (get results key1))))
            results))
    
    => {:D 5, :C 2, :A 1}
    
    ;; To make sure that the sorting works, we can make sure that the comparator 
    ;; works on unique values
    
    user=> (let [results {:A 1 :B 2 :C 2 :D 5 :E 1 :F 1}]
      (into (sorted-map-by (fn [key1 key2]
                             (compare [(get results key2) key2]
                                      [(get results key1) key1])))
            results))
    
    => {:D 5, :C 2, :B 2, :F 1, :E 1, :A 1}
Log in to add / edit an example.

See Also top

Log in to add a see also.

Plus_12x12 Minus_12x12 Source clojure/core.clj:343 top

(defn sorted-map-by
  "keyval => key val
  Returns a new sorted map with supplied mappings, using the supplied comparator."
  {:added "1.0"}
  ([comparator & keyvals]
   (clojure.lang.PersistentTreeMap/create comparator keyvals)))
Vars in clojure.core/sorted-map-by: comparator defn
Used in 0 other vars

Comments top

No comments for sorted-map-by. Log in to add a comment.