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

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

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

提交回复
热议问题