What is a Map in Clojure?
Overview
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
- Sorted maps
Hash 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:
Example
(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)
Explanation
Let's look at the explanation of the code above:
- Line 3: We define the function
createMap. - Line 4: We define a variable,
exampleMap, and assign our map to it. The map is created using thehash-mapfunction. - Line 5: We use the
printlnto print the created map (exampleMap). - Line 6: We call the
createMapfunction. This creates the hash map and prints its elements. Notice that the elements are printed in a random order.
Sorted maps
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:
Example
(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)
Explanation
Let's look at the explanation of the code above:
- Line 3: We define the function
keyss. - Line 4: We define a variable,
exampleMap, and assign our map to it. We use thesorted-mapmethod to create the map. - Line 5: We add a statement to print the created map using the
printlnmethod. - Line 6: We call the
createSortedMapfunction. This creates the sorted map and prints its elements. Notice that the elements are printed in a sorted order based on the keys.