Muhtar Lupen
Muhtar Lupen

Reputation: 13

What is the Scala way of summing fields of list of tuples?

I want to reduce list of tuples that have a common field such as x by summing y fields.

Input:

List(("x" -> "foo", "y" -> 1000),
     ("x" -> "foo", "y" -> 1),
     ("x" -> "bar", "y" -> 101))

Output:

List(("x" -> "foo", "y" -> 1001),
     ("x" -> "bar", "y" -> 101))

What is the good approach for that? foldLeft or reduce?

Upvotes: 1

Views: 138

Answers (1)

chengpohi
chengpohi

Reputation: 14227

Your item should be tuple:

List(("x" -> "foo", "y" -> 1000),("x" -> "foo", "y" -> 1), ("x" -> "bar", "y" -> 101))

use groupBy to group your key, and mapValues to generate the target:

List(("x" -> "foo", "y" -> 1000),("x" -> "foo", "y" -> 1), ("x" -> "bar", "y" -> 101))
 .groupBy(x => x._1)
 .mapValues(t => t.head._2._1 -> t.foldLeft(0.0)(_ + _._2._2))

The Output:

scala.collection.immutable.Map[(String, String),(String, Double)] = 
    Map((x,foo) -> (y,1001.0), (x,bar) -> (y,101.0))

Upvotes: 1

Related Questions