简体   繁体   English

如何在Scala中迭代map的值?

[英]How to iterate values of map in Scala?

For the value 为了价值
val m = Map(2 ->(3, 2), 1 ->(2, 1))

I want to add up elements belonged to same key, thus, the result is : 我想将属于同一键的元素加起来,结果是:
Map(2 -> 5,1 -> 3)

Please guys help me how to solve this problem, I'll appreciate any help! 请大家帮我解决这个问题,我们将不胜感激!

Consider 考虑

m.mapValues { case(x,y) => x+y }

which creates a new Map with same keys and computed values. 这会创建一个具有相同键和计算值的新Map Also consider 还考虑

def f(t: (Int,Int)) = t._1+t._2

and so a more concise approach includes this 所以更简洁的方法包括

m.mapValues(f)

Note Decomposing tuples in function arguments for details in declaring a function that can take the tuples from the Map . 注意在函数参数中分解元组以获取声明可以从Map 元组的函数的详细信息。

Update Following important note by @KevinMeredith (see link in comment below), mapValues provides a view to the collection and the transformation needs be referentially transparent; 更新 @KevinMeredith的重要说明(请参阅下面的注释中的链接)之后, mapValues提供了该集合的视图,并且转换需要参照透明; hence as a standard (intuitive) approach consider pattern-matching on the entire key-value group using map for instance like this, 因此,作为一种标准(直观)方法,请考虑使用map这样对整个键值组进行模式匹配,例如,

m.map { case (x,(t1,t2)) => x -> (t1+t2) }

or 要么

m.map { case (k,v) => (k,f(v)) }

or 要么

for ( (x,(t1,t2)) <- m ) yield x -> (t1+t2) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM