A map is a collection that holds key-value pairs. The values stored in the map can be accessed using the corresponding key. In Clojure there are two types of maps:
Hash maps are created using the hash-map
function. Their keys support hashCode
and equals
. Let's see an example of a hash map:
(ns clojure.examples.createMap(:gen-class))(defn createMap [](def example (hash-map "x" "10" "y" "52" "z" "93"));the use of the hash-map method(println example))(createMap)
Let's look at the explanation of the code above:
createMap
.exampleMap
, and assign our map to it. The map is created using the hash-map
function.println
to print the created map (exampleMap
).createMap
function. This creates the hash map and prints its elements. Notice that the elements are printed in a random order.Sorted maps are created using the sorted-map
function. The keys for a sorted map implement an instance of Comparable
. The elements of the sorted map are sorted according to their keys. Let's take a look at an example of a sorted map:
(ns clojure.examples.createSortedMap(:gen-class))(defn createSortedMap [](def exampleMap (sorted-map "z" "10" "y" "52" "x" "93")); notice the use of the sorted-map method(println exampleMap))(createSortedMap)
Let's look at the explanation of the code above:
keyss
.exampleMap
, and assign our map to it. We use the sorted-map
method to create the map.println
method.createSortedMap
function. This creates the sorted map and prints its elements. Notice that the elements are printed in a sorted order based on the keys.