Tg. Tg. - 4 months ago 23
Scala Question

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

I was thinking about a nice way to convert a List of tuple with duplicate key

[("a","b"),("c","d"),("a","f")]
into map
("a" -> ["b", "f"], "c" -> ["d"])
. Normally (in python), I'd create an empty map and for-loop over the list and check for duplicate key. But I am looking for something more scala-ish and clever solution here.

btw, actual type of key-value I use here is
(Int, Node)
and I want to turn into a map of
(Int -> NodeSeq)

Answer

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).