Over a million developers have joined DZone.

Clojure: Updating keys in a map

· Java Zone

Easily build powerful user management, authentication, and authorization into your web and mobile applications. Download this Forrester report on the new landscape of Customer Identity and Access Management, brought to you in partnership with Stormpath.

I’ve been playing with Clojure over the last few weeks and as a result I’ve been using a lot of maps to represent the data.

For example if we have the following map of teams to Glicko ratings and ratings deviations:

(def teams { "Man. United" {:points 1500 :rd 350} 
             "Man. City"   {:points 1450 :rd 300} })

We might want to increase Man. United’s points score by one for which we could use the update-in function:

> (update-in teams ["Man. United" :points] inc)
{"Man. United" {:points 1501, :rd 350}, "Man. City" {:points 1450, :rd 300}}

The 2nd argument to update-in is a nested associative structure i.e. a sequence of keys into the map in this instance.

If we wanted to reset Man. United’s points score we could use assoc-in:

> (assoc-in teams ["Man. United" :points] 1)
{"Man. United" {:points 1, :rd 350}, "Man. City" {:points 1450, :rd 300}}

If we want to update multiple keys at once then we can chain them using the -> (thread first) macro:

(-> teams
    (assoc-in ["Man. United" :points] 1600)
    (assoc-in ["Man. United" :rd] 200))
{"Man. United" {:points 1600, :rd 200}, "Man. City" {:points 1450, :rd 300}}

If instead of replacing just one part of the value we want to replace the whole entry we could use associnstead:

> (assoc teams "Man. United" {:points 1600 :rd 300})
{"Man. United" {:points 1600, :rd 300}, "Man. City" {:points 1450, :rd 300}}

assoc can also be used to add a new key/value to the map. e.g.

> (assoc teams "Arsenal" {:points 1500 :rd 330})
{"Man. United" {:points 1500, :rd 350}, "Arsenal" {:points 1500, :rd 330}, "Man. City" {:points 1450, :rd 300}}

dissoc plays the opposite role and returns a new map without the specified keys:

> (dissoc teams "Man. United" "Man. City")
{}

And those are all the map based functions I’ve played around with so far…

The Java Zone is brought to you by Stormpath—a complete, pre-built User Management API. Want to learn how to use JWTs to protect microservices from CSRF and more? Check out this on-demand webinar with our Java Developer Evangelist, Micah Silverman.

Topics:

Published at DZone with permission of Mark Needham, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}