Some Functions With Maps

Here are some functions with maps.


;; you can create a map directly (the commas are optional)
user.core=> (def my-map {:a "this is a", :b "this is b", "hello" "there"})
user.core=> my-map
{:a "this is a", :b "this is b", "hello" "there"}
user.core=> (class my-map)
user.core=> (def my-second-map (hash-map :a "value a", :b "value b", :c 33))
user.core=> my-second-map
{:c 33, :b "value b", :a "value a"}
user.core=> (class my-second-map)
user.core=> (def my-third-map (sorted-map :a "value a" :b "value b" :c 33))
user.core=> my-third-map
{:a "value a", :b "value b", :c 33}
user.core=> (class my-third-map)
;; you can get a value by using the key as a function
user.core=> (:c my-second-map)
;; or with get
user.core=> (get my-second-map :b)
"value b"
;; you can supply a default value as well just in case
user.core=> (get my-second-map :b "no such key")
"value b"
user.core=> (get my-second-map :d "no such key")
"no such key"
;; strings as keys are not a good idea
user.core=> (get my-map "hello")
user.core=> ("hello" my-map)

ClassCastException java.base/java.lang.String cannot be cast to clojure.lang.IFn  user.core/eval9972 (form-init5882881271358286795.clj:1)
;; you can also use the map as a function to get a key's value
user.core=> (my-map :a)
"this is a"
user.core=> (my-map "hello")

;; add a key and a value with assoc
user.core=> (assoc my-map :d "what is this?")
{:a "this is a", :b "this is b", "hello" "there", :d "what is this?"}
;; adding to a sorted map will add the key in the proper place
user.core=> (assoc my-third-map :be "or not to be")
{:a "value a", :b "value b", :be "or not to be", :c 33}
;; but not change the original map
user.core=> my-third-map
{:a "value a", :b "value b", :c 33}

You’re welcome.

There are 319 words in this article.