A map is a collection that assigns keys to values.
map-invert
map method in Clojure?The map-invert
method is used to turn keys to values and values to keys in a map.
(map-invert hmap)
The map-invert method receives one parameter:
hmap
: The map we are working with.
The map-invert
method returns an inverted map.
(ns clojure.examples.example(:require [clojure.set :as set])(:gen-class))(defn invert [](def example (hash-map "z" "98" "x" "90" "u" "53"))(println (set/map-invert example)))(invert)
Notice how in the code above the output now has an inverted map.
Line 2: We include the set
package like so;(:require [clojure.set :as set])
Lines 3–4: We define the function invert
.
In line 5: We use the keyword def
to define a variable example
and we assign our map to it.
In line 6: We use the map-invert
method to invert the map example
keys and values using the method as; (set/map-invert example)
In line 7: We call the invert
function.