Maps in Clojure
Maps are Clojure’s built-in associative data type (sometimes called hashes or dicts in other languages).
To create an empty map, use the hash-map
function or the {}
syntax.
Set key/value pairs using typical assoc
.
Printing a map using println
will show all of its key/value pairs.
Get a value for a key with (get map key)
.
If the key doesn’t exist, the zero value of the value type is returned.
The count
function returns the number of key/value pairs when called on a map.
The dissoc
function removes key/value pairs from a map.
To remove all key/value pairs from a map, you can simply create a new, empty map.
The optional second return value when getting a value from a map via destructuring indicates if the key was present in the map. This can be used to disambiguate between missing keys and keys with zero values like 0
or ""
.
You can also declare and initialize a new map in the same line with this syntax.
Clojure provides several useful functions for working with maps in the core library.
Note that maps appear in the form {"k" v, "k" v}
when printed with println
.