Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala sum By Key function

Tags:

scala

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 !

like image 865
Momog Avatar asked Dec 13 '25 16:12

Momog


1 Answers

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.

like image 106
dhg Avatar answered Dec 15 '25 21:12

dhg