我希望通过对y字段求和来减少具有x等公共字段的元组列表。
输入:
List(("x" -> "foo", "y" -> 1000),
("x" -> "foo", "y" -> 1),
("x" -> "bar", "y" -> 101))
输出:
List(("x" -> "foo", "y" -> 1001),
("x" -> "bar", "y" -> 101))
有什么好处? foldLeft还是reduce?
答案 0 :(得分:1)
你的项目应该是元组:
List(("x" -> "foo", "y" -> 1000),("x" -> "foo", "y" -> 1), ("x" -> "bar", "y" -> 101))
使用groupBy
对您的密钥进行分组,并mapValues
生成目标:
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))
输出 :
scala.collection.immutable.Map[(String, String),(String, Double)] =
Map((x,foo) -> (y,1001.0), (x,bar) -> (y,101.0))