Merging and splitting collections

Sometimes, you'd like to merge multiple collections into a single collection or split a single collection into multiple collections. Let's have a look these cases.

Getting ready

You only need REPL, described in the Repl up! recipe in Chapter 1, Live Programming with Clojure, and no additional libraries. Start REPL, and you can review the sample code in this recipe.

How to do it...

Let's see how to merge and split collections.

Using merge and merge-with for merging

The merge function merges multiple maps into a single map. If there are the same keys among maps in arguments, latter entries override former entries:

(merge {:a 1 :b 2 :c 3} {:c 4 :d 5 :e 6}) ;;=> {:a 1, :b 2, :c 4, :d 5, :e 6} (merge {:a 1 :b 2 :c 3} {:c ...

Get Clojure Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.