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\", \"
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:
group
s elements based on the first part of tuples (group part of groupMap)
map
s 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.