Over a million developers have joined DZone.

Clojure: Merge Two Maps but Only Keep the Keys of One of Them

· Java Zone

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

I’ve been playing around with Clojure maps recently and I wanted to merge two maps of rankings where the rankings in the second map overrode those in the first while only keeping the teams from the first map.

The merge function overrides keys in earlier maps but also adds keys that only appear in later maps. For example, if we merge the following maps:

> (merge {"Man. United" 1500 "Man. City" 1400} {"Man. United" 1550 "Arsenal" 1450})
{"Arsenal" 1450, "Man. United" 1550, "Man. City" 1400}

we get back all 3 teams but I wanted a function which only returned ‘Man. United’ and ‘Man. City’ since those keys appear in the first map and ‘Arsenal’ doesn’t.

wrote the following function:

(defn merge-rankings [initial-rankings override-rankings]
  (merge initial-rankings
         (into {} (filter #(contains? initial-rankings (key %)) override-rankings))))

If we call that we get the desired result:

> (merge-rankings {"Man. United" 1500 "Man. City" 1400} {"Man. United" 1550 "Arsenal" 1450})
{"Man. United" 1550, "Man. City" 1400}

An alternative version of that function could use select-keys like so:

(defn merge-rankings [initial-rankings override-rankings]
  (select-keys (merge initial-rankings override-rankings) (map key initial-rankings)))

bitemyapp points out in the comments that we can go even further and use the keys function instead of map key, like so:

(defn merge-rankings [initial-rankings override-rankings]
  (select-keys (merge initial-rankings override-rankings) (keys initial-rankings)))

Now let’s generify the function so it would make sense in the context of any maps, not just ranking related ones:

(defn merge-keep-left [left right]
  (select-keys (merge left right) (keys left)))

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

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 }}