给定一个数组如下:
val stats: Array[(Int, (Double, Int))]=Array((4,(2,5)), (4,(8,4)), (7,(10,0)), (1,(1,3)), (4,(7,9)))
当按键分组时,如何获得对的第一个元素的总和! 例如,对于键值 4,我必须将这些值相加 2.0 + 8.0 + 7.0
result = Array((4, 17.0), (7, 10.0), (1, 1.0))
我开始这样做,但我不知道如何继续:
stats.groupBy(_._1) mapValues (_.map(_._2)) //....
感谢您的帮助!
最佳答案
这就是您要找的:
stats.groupBy(_._1).mapValues(_.map(_._2._1).sum).toArray
// Array((4,17.0), (7,10.0), (1,1.0))
你已经很接近了,你只需要捕获 ._2._1
,即b
在 (a,(b,c))
目的。然后您可以对这些值求和。
关于scala sum By Key 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29286891/