我想按键
组合此列表的值List((1, 11), (2, 21), (1, 13), (1, 14), (2, 25))
并获得如下列表:
List((1, List(11, 13, 14)), (2, List(21, 25)))
我正在考虑为每个元素使用groupBy然后使用reduceLeft,但我认为可能有更简单,更直接的方式?
答案 0 :(得分:5)
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)))
答案 1 :(得分:2)
这类似于@Brians解决方案,但使用模式匹配:
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)))
如果您对Map作为结果类型没问题,可以稍微缩短一下:
xs.groupBy(_._1).map { case (k, v) => (k, v.map(_._2))}
或:
xs.groupBy(_._1).map { t => (t._1, t._2.map(_._2))}