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

前端 未结 8 2145
[愿得一人]
[愿得一人] 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:29

    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")) 
    
    0 讨论(0)
  • 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))
    
    0 讨论(0)
提交回复
热议问题