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

前端 未结 8 2153
[愿得一人]
[愿得一人] 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")) 
    

提交回复
热议问题