Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Clojure: Updating keys in a map

DZone's Guide to

Clojure: Updating keys in a map

· Java Zone
Free Resource

Build vs Buy a Data Quality Solution: Which is Best for You? Gain insights on a hybrid approach. Download white paper now!

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…

Build vs Buy a Data Quality Solution: Which is Best for You? Maintaining high quality data is essential for operational efficiency, meaningful analytics and good long-term customer relationships. But, when dealing with multiple sources of data, data quality becomes complex, so you need to know when you should build a custom data quality tools effort over canned solutions. Download our whitepaper for more insights into a hybrid approach.

Topics:

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

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}