假设我有一个清单:
[(A, a), (A, b), (A, c), (B, a), (B, d)]
如何将该列表设为:
[(A, [a,b,c]), (B, [a,d])]
只有一个功能?
由于
答案 0 :(得分:3)
groupBy功能可以实现此目的:
scala> val list = List((1, 'a'), (1, 'b'), (1, 'c'), (2, 'a'), (2, 'd'))
list: List[(Int, Char)] = List((1,a), (1,b), (1,c), (2,a), (2,d))
scala> list.groupBy(_._1) // grouping by the first item in the tuple
res0: scala.collection.immutable.Map[Int,List[(Int, Char)]] = Map(2 -> List((2,a), (2,d)), 1 -> List((1,a), (1,b), (1,c)))
答案 1 :(得分:0)
只是做groupBy不会给你想要的预期格式。所以我建议你为此编写一个自定义方法。
def groupTuples[A,B](seq: Seq[(A,B)]): List[(A, List[B])] = {
seq.
groupBy(_._1).
mapValues(_.map(_._2).toList).toList
}
然后调用它以获得所需的结果。
val t = Seq((1,"I"),(1,"AM"),(1, "Koby"),(2,"UP"),(2,"UP"),(2,"AND"),(2,"AWAY"))
groupTuples[Int, String](t)