给定一个数组,如下所示:
val stats: Array[(Int, (Double, Int))]=Array((4,(2,5)), (4,(8,4)), (7,(10,0)), (1,(1,3)), (4,(7,9)))
Run Code Online (Sandbox Code Playgroud)
按键分组时,如何获取对的第一个元素的总和!例如,对于键值4,我必须将这些值相加2.0 + 8.0 + 7.0
result = Array((4, 17.0), (7, 10.0), (1, 1.0))
Run Code Online (Sandbox Code Playgroud)
我从这样做开始,但是我不知道如何继续:
stats.groupBy(_._1) mapValues (_.map(_._2)) //....
Run Code Online (Sandbox Code Playgroud)
感谢帮助 !
这是您要寻找的:
stats.groupBy(_._1).mapValues(_.map(_._2._1).sum).toArray
// Array((4,17.0), (7,10.0), (1,1.0))
Run Code Online (Sandbox Code Playgroud)
你很接近,你只需要抢._2._1,这是b在(a,(b,c))对象。然后,您可以将这些值求和。