1

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?

1 Answers1

1

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))
The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
chengpohi
  • 14,064
  • 1
  • 24
  • 42