ClojureDocs

Nav

Namespaces

max-key

clojure.core

Available since 1.0 (source)
  • (max-key k x)
  • (max-key k x y)
  • (max-key k x y & more)
Returns the x for which (k x), a number, is greatest.
 If there are multiple such xs, the last one is returned.
5 Examples
user=> (max-key count "asd" "bsd" "dsd" "long word")
"long word"
; find the key that has the highest value in a map
user=> (key (apply max-key val {:a 3 :b 7 :c 9}))
:c
;; find the index of the highest value. Equivalent to an 'argmax' function
user=> (first (apply max-key second (map-indexed vector '(2 1 6 5 4))))
2
;; find the max :timestamp in a collection of maps.
user=> (def mmm [
  {:timestamp 1 :name "v"} 
  {:timestamp 2 :name "q"} 
  {:timestamp 3 :name "r"}])

user=> (apply max-key :timestamp mmm)
{:timestamp 3, :name "r"}

user=> (:timestamp (apply max-key :timestamp mmm))
3

;;if the map is indexed by item-id, use an anonymous function where the key goes.

user=> (def map-with-index {
  "gary" {:timestamp 1 :name "v"} 
  "carl" {:timestamp 2 :name "q"} 
  "lola" {:timestamp 3 :name "r"}})

user=> (apply max-key #(:timestamp (val %)) map-with-index)
["lola" {:timestamp 3, :name "r"}]

;notice how we replaced :timestamp with #(:timestamp (val %)) 
;to get the inner value [and not the (key %)] of the indexed version.
;; filter out the the biggest map based on the size

user=>  (def maps [{:a 1 :b 2}
                   {:a 1}
                   {:a 1 :b 2 :c 3}
                   {:a 1 :b 2 :c 3 :d 4}])

user=> (apply max-key count maps)
{:a 1 :b 2 :c 3 :d 4}

;; in a case when multiple maps are of the same size, returns the last
;; biggest map it encounters 
See Also

Returns the greatest of the nums.

Added by gstamp

Returns the x for which (k x), a number, is least. If there are multiple such xs, the last one is...

Added by adereth

Returns the least of the nums.

Added by mhmdsalem1993
0 Notes
No notes for max-key