按第一个元素分组数组

时间:2015-12-07 07:39:54

标签: scala scala-collections

我有一个像这样的数组[(Int,(Int,Int))],

   (24, (12, 5))
   (12, (17, 3))
   (1,  (7, 25))
   (24, (4, 6))
   (1,  (13, 3))
   (12, (9, 14))
   (24, (9, 18))

我想用第一个元素对这些数组进行分组,这意味着我希望:

   (24, ((12, 5), (4, 6), (9, 18)))
   (12, ((17, 3), (9, 14)))
   (1,  ((7, 25), (13, 3)))  

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:6)

所以你有:

val arr = Array((24, (12, 5)), (12, (17, 3)), (1,  (7, 25)), (24, (4, 6)), (1,  (13, 3)), (12, (9, 14)), (24, (9, 18)))

您可以使用组方法进行分组:

val grouped = arr.groupBy(_._1).map {case (k,v) => k -> v.map {case (_, (b,c))=> (b,c)}}

或:

val grouped = arr.groupBy(_._1).mapValues {_.map {case (_, (b,c))=> (b,c)}}