Convert List of tuple to map (and deal with duplic

2019-01-21 04:15发布

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)

标签: scala map
8条回答
Viruses.
2楼-- · 2019-01-21 05:13

Here is a more Scala idiomatic way to convert a list of tuples to a map handling duplicate keys. You want to use a fold.

val x = List("a" -> "b", "c" -> "d", "a" -> "f")

x.foldLeft(Map.empty[String, Seq[String]]) { case (acc, (k, v)) =>
  acc.updated(k, acc.getOrElse(k, Seq.empty[String]) ++ Seq(v))
}

res0: scala.collection.immutable.Map[String,Seq[String]] = Map(a -> List(b, f), c -> List(d))
查看更多
劳资没心,怎么记你
3楼-- · 2019-01-21 05:15

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")) 
查看更多
登录 后发表回答