How to associate a map in Clojure

In Clojure, we can associate a map using the associate function (aka assoc). It has two modes of application:

  1. If applied to a map, it produces a new map having the same type (hashed/sorted) while associating the selected key with the chosen value.

  2. If applied to a vector, it provides a new vector containing a value v at an index k, provided the index is less than the vector count.

Let's look at the following examples:

Example 1

This example revolves around adding a new key-value pair to a given map:

(def userInfo {:name "Bassem" :userID 5 })
(print (assoc userInfo :age 45))

Let's explain the code widget stated above:

  • Line 1: Define a map holding some user information.

  • Line 2: Associate a new attribute age to the map and display the result.

Example 2

This example focuses on changing the value corresponding to an existing key in a given map:

(def userInfo {:name "Bassem" :userID 5 })
(print (assoc userInfo :userID 5 :name "Bassem Marji"))

Let's explain the code widget stated above:

  • Line 1: Define a map holding some user information.

  • Line 2: Change the name associated with a specific key userID and display the result.

Example 3

This example shows how to replace a value at a specified index in a vector:

(print(assoc [1 2 3 4 5] 2 7))

Let's explain the code widget stated above:

  • Line 1: Define a vector containing a sequence of numbers, and change the value of the number located at the index 2–7, knowing that the index of the vector elements always starts at zero. Finally, print out the result.

Free Resources

Copyright ©2026 Educative, Inc. All rights reserved