Need to merge multiple maps by their keys and make manipulation on the values?  this post is probably for you!

Why ?
previous experience with map reduce, many times data collected was in a Map structure, found myself repeatedly summing/appending/listing/manipulating maps


  • Assuming we have 2 maps with names of people as the key and the amount of them as the value :

  • For some reason we need to merge the 2 maps into 1 expecting to sum the values and get all keys.

  • Lets write our own implementation for this task :

  • Next task: lets merge the maps but instead of summing the values lets list them

  • Ok that was nice, but can be achieved much easier using Scalaz semigroups


Main idea with using scalaz |+| is to arrange the data structure to what you need to do. in case you need to sum values a int will do the job. case you need to list the values a list of Any will do the trick.

This example really comes in handy when used in reduce functions, resulting in clean and short code (if you aren’t a scalaz hater)

Share Button