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

前端 未结 8 2147
[愿得一人]
[愿得一人] 2020-12-12 14:32

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\", \"

8条回答
  •  北海茫月
    2020-12-12 15:30

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

提交回复
热议问题