How to write hash maps in Clojure

In Clojure, a hash map is a collection of values mapped to keys.

This key/value pair data structure is commonly represented by the syntax {key:value} and is mainly helpful for the following:

  • Defining self-describing structured data

  • Associating different values with each other

In hash maps, it is common for keys to be defined by keywords, although strings or anything else can also be used. Using keywords makes it easier to extract or manipulate values in a map.

Let's explore the different options for creating and defining hash maps.

Example 1

The example below shows how to create a hash map by implementing a string value as a key:

(def user {"name" "Bassem" "Address" "Lebanon" "age" 45})
(println "The user information are:" user)

In the code widget above, we defined a map containing user-related information, then we displayed this map.

Example 2

The example below shows how to create a hash map while naming the keys as keywords:

(def user {:name "Bassem" :Address "Lebanon" :age 45})
(println "The user information are:" user)

In the code widget above, we defined a map containing user-related information while using the keywords (:name, :Address, :age), then we displayed this map.

Example 3

The example below shows how to define a hash map using the constructor function:

(def user (hash-map :name "Bassem" :Address "Lebanon" :age 45))
(println "The user information are:" user)

In the code widget above, we defined a map containing user-related information while using the respective constructor hash-map.

Example 4

The example below shows how to create a hash map by converting another collection like a sequence to a hash map:

(def user (apply hash-map [:name "Bassem" :Address "Lebanon" :age 45]))
(println "The user information are:" user)

Let's explain the code widget above:

  • Line 1: Invoke the function apply to create a hash map out of the specified sequence. Basically, this function destructures a collection before processing it, meaning by that converting it to a hash map.

  • Line 2: Display the hash map created after the conversion.

Copyright ©2024 Educative, Inc. All rights reserved