It is a Monoid
Hark back a bit dear reader. If you recall, we had said that a Monoid needs to be associative and should have an identity value.
Instead of using groupBy
and friends, we can instead think of the collections as monoids and use foldLeft
. Here is an example of how we do this:
scala> val list = List("x" -> "y", "z" -> "c", "x" -> "p", "z" -> "d") // 1 list: List[(String, String)] = List((x,y), (z,c), (x,p), (z,d)) scala> Map[String, List[String]]() // 2 acc: scala.collection.immutable.Map[String,List[String]] = Map() scala> list.foldLeft(acc) { (a, b) => | a + (b._1 -> (b._2 :: a.getOrElse(b._1, Nil))) | } // 3 res0: scala.collection.immutable.Map[String,List[String]] = Map(x -> List(p, y), z -> List(d, c))
The salient points of the preceding code are as follows:
Here, we have an input list of pairs that we need to convert into a map.
As the identity value, we have an empty
HashMap
function.We use the
foldLeft
accumulator in the preceding...