I am a quite new in scala and trying to learn especially collections. I couldn't find a way to sum of the second column by group bying the first one. My data is as follows:
val a2 = List(("Comedy",2.0),
("Comedy",2.5),
("Adv",3.0),
("Adv",2.5)
My aim is to use group by 1st sum the 2nd one:
Comedy, 4.5
Adv, 5.5
I did group by but .sum(i => i._2) didn't work. Do you know the way to do that?
CodePudding user response:
You can use groupBy before sum:
List(
("Comedy", 2.0),
("Comedy", 2.5),
("Adv", 3.0),
("Adv", 2.5)
)
.groupBy(_._1)
.map(group => (group._1, group._2.map(_._2).sum))
.foreach(println)