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

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

    Starting Scala 2.13, most collections are provided with the groupMap method which is (as its name suggests) an equivalent (more efficient) of a groupBy followed by mapValues:

    List("a" -> "b", "c" -> "d", "a" -> "f").groupMap(_._1)(_._2)
    // Map[String,List[String]] = Map(a -> List(b, f), c -> List(d))
    

    This:

    • groups elements based on the first part of tuples (group part of groupMap)

    • maps grouped values by taking their second tuple part (map part of groupMap)

    This is an equivalent of list.groupBy(_._1).mapValues(_.map(_._2)) but performed in one pass through the List.

提交回复
热议问题