Clojure - Maps


Advertisements


A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.

A map can be created in two ways, the first is via the hash-map method.

Creation - HashMaps

HashMaps have a typical key value relationship and is created by using hash-map function.

Live Demo
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (hash-map "z" "1" "b" "2" "a" "3"))
   (println demokeys))
(example)

Output

The above code produces the following output.

{z 1, b 2, a 3}

Creation - SortedMaps

SortedMaps have the unique characteristic of sorting their elements based on the key element. Following is an example that shows how the sorted map can be created using the sorted-map function.

Live Demo
(ns clojure.examples.example
   (:gen-class))
(defn example []
   (def demokeys (sorted-map "z" "1" "b" "2" "a" "3"))
   (println demokeys))
(example)

The above code produces the following output.

{a 3, b 2, z 1}

From the above program you can clearly see that elements in the maps are sorted as per the key value. Following are the methods available for maps.

Sr.No. Maps & Description
1 get

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

2 contains?

See whether the map contains a required key.

3 find

Returns the map entry for the key.

4 keys

Returns the list of keys in the map.

5 vals

Returns the list of values in the map.

6 dissoc

Dissociates a key value entry from the map.

7 merge

Merges two maps entries into one single map entry.

8 merge-with

Returns a map that consists of the rest of the maps conj-ed onto the first.

9 select-keys

Returns a map containing only those entries in map whose key is in keys.

10 rename-keys

Renames keys in the current HashMap to the newly defined ones.

11 map-invert

Inverts the maps so that the values become the keys and vice versa.



Advertisements