Given an array as follows:
val stats: Array[(Int, (Double, Int))]=Array((4,(2,5)), (4,(8,4)), (7,(10,0)), (1,(1,3)), (4,(7,9)))
How can I get the sum of the 1st elements of pairs when grouped by key !!! For example, for the key value 4, I've to sum these values 2.0 + 8.0 + 7.0
result = Array((4, 17.0), (7, 10.0), (1, 1.0))
I started by doing this but I don't how to continue:
stats.groupBy(_._1) mapValues (_.map(_._2)) //....
Thanks for help !
This is what you're looking for:
stats.groupBy(_._1).mapValues(_.map(_._2._1).sum).toArray
// Array((4,17.0), (7,10.0), (1,1.0))
You're pretty close, you just need to grab ._2._1, which is b in the (a,(b,c)) object. And then you can sum those values.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With