Question

I want to combine the values of this list by key

List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25))

and obtain a list like this:

List((1, List(11, 13, 14)), (2, List(21, 25)))

I am thinking of using a groupBy and then a reduceLeft for each element, but I think there may be an easier, more direct way?

Was it helpful?

Solution

scala> val l = List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25))
l: List[(Int, Int)] = List((1,11), (2,21), (1,13), (1,14), (2,25))


scala> l.groupBy(_._1).toList.map(xs => (xs._1, xs._2.map(t => t._2)))
res0: List[(Int, List[Int])] = List((2,List(21, 25)), (1,List(11, 13, 14)))

OTHER TIPS

This is similar to @Brians solution, but uses pattern matching:

scala> val xs = List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25))
l: List[(Int, Int)] = List((1,11), (2,21), (1,13), (1,14), (2,25))

xs.groupBy(_._1).toList.map { case (k, v) => (k, v.map(_._2)) }
res13: List[(Int, List[Int])] = List((1,List(11, 13, 14)), (2,List(21, 25)))

If you are ok with Map as result type you can shorten it a bit:

xs.groupBy(_._1).map { case (k, v) => (k, v.map(_._2))}

or:

xs.groupBy(_._1).map { t => (t._1, t._2.map(_._2))}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top