Sum of items based on item grouping with scala?

I have the following scala list-

    List((192.168.1.1,8590298237), (192.168.1.1,8590122837), (192.168.1.1,4016236988),
 (192.168.1.1,1018539117), (192.168.1.1,2733649135),  (192.168.1.2,16755417009), 
(192.168.1.1,3315423529), (192.168.1.2,1523080027), (192.168.1.1,1982762904), 
(192.168.1.2,6148851261), (192.168.1.1,1070935897), (192.168.1.2,276531515092), 
(192.168.1.1,17180030107), (192.168.1.1,8352532280), (192.168.1.3,8590120563), 
(192.168.1.3,24651063), (192.168.1.3,4431959144), (192.168.1.3,8232349877), 
(192.168.1.2,17493253102), (192.168.1.2,4073818556),   (192.168.1.2,42951186251))

      

I need the following output -

List((192.168.1.1, sum of all values of 192.168.1.1),
(192.168.1.2, sum of all values of 192.168.1.2),
(192.168.1.3, sum of all values of 192.168.1.3))

      

How do I get the sum of the second elements from a list by grouping the first element using scala ??

+3


source to share


1 answer


Here's how you can use a function groupBy

in Scala. You, however, have some problems in your input, ip numbers or whatever, these are Longs strings and numbers. Below is an example of a function groupBy

:

val data = ??? // Your list
val sumList = data.groupBy(_._1).map(x => (x._1, x._2.map(_._2).sum)).toList

      



If the answer is correct, please accept it or comment and I will explain a little more.

+3


source







All Articles