get

added
1.0

ns
clojure.core

type
function

(get map key) (get map key not-found)

Returns the value mapped to key, not-found or nil if key not present.

                (get [1 2 3] 1)
;;=> 2

(get [1 2 3] 5)
;;=> nil

(get {:a 1 :b 2} :b)
;;=> 2

(get {:a 1 :b 2} :z "missing")
;;=> "missing"


            
                ;; to get an index of the element of a vector, use .indexOf
(def v ["one" "two" "three" "two"])
;; #'user/v

(.indexOf v "two")
;;=> 1

(.indexOf v "foo")
;;=> -1

            
                ;; the system environment has a hash-map semantic
(get (System/getenv) "SHELL")
;;=> "/bin/bash"

(get (System/getenv) "PATH")
;;=> "/usr/local/bin:/sbin:/usr/sbin:/usr/bin:/bin"
            
                ;; 'get' is not the only option
(def my-map {:a 1 :b 2 :c 3})

;; maps act like functions taking keys 
(my-map :a)
;;=> 1

;; even keys (if they are keywords) act like functions
(:b my-map)
;;=> 2
            
                ;; it is tempting to try an index on a list
(get '(a b c) 1)
;;=> nil

;; but you should use nth
(nth '(a b c) 1)
;;=> b
            
                ;; Get also works with strings:
(get "abc" 1)
;;=> \\b
            
                ;; For sorted stuff, "key" must be of the same type of the existing keys. 
;; This allows descending the sorted tree in log(N) average.

(get (hash-map :a 1 :b 2) "a" "not found")
;; "not found"

(get (sorted-map :a 1 :b 2) "a" "not found")
;; ClassCastException

;; get works on transient maps, but silently fails on transient sets.
;; A similar issue affects contains?.

(get (transient #{0 1 2}) 1)
;; nil

;; get uses int cast with precision loss, with (.intValue x).
;; The example below is explained because 4294967296 equal 2^32, thus
;; (.intValue 4294967296) returns 0.
;; Be careful with sufficiently large keys:

(get ["a" "b" "c"] 4294967296)
;; "a"