Convert List of tuple to map (and deal with duplicate key ?)

For Googlers that don't expect duplicates or are fine with the default duplicate handling policy:

List("a" -> 1, "b" -> 2).toMap
// Result: Map(a -> 1, c -> 2)

As of 2.12, the default policy reads:

Duplicate keys will be overwritten by later keys: if this is an unordered collection, which key is in the resulting map is undefined.


Group and then project:

scala> val x = List("a" -> "b", "c" -> "d", "a" -> "f")
//x: List[(java.lang.String, java.lang.String)] = List((a,b), (c,d), (a,f))
scala> x.groupBy(_._1).map { case (k,v) => (k,v.map(_._2))}
//res1: scala.collection.immutable.Map[java.lang.String,List[java.lang.String]] = Map(c -> List(d), a -> List(b, f))

More scalish way to use fold, in the way like there (skip map f step).


Here's another alternative:

x.groupBy(_._1).mapValues(_.map(_._2))

For Googlers that do care about duplicates:

implicit class Pairs[A, B](p: List[(A, B)]) {
  def toMultiMap: Map[A, List[B]] = p.groupBy(_._1).mapValues(_.map(_._2))
}

> List("a" -> "b", "a" -> "c", "d" -> "e").toMultiMap
> Map("a" -> List("b", "c"), "d" -> List("e"))