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!
Asked
Active
Viewed 50 times
0

Soumyaansh
- 8,626
- 7
- 45
- 45

高源伯
- 367
- 4
- 4
-
1have u tried any code ?? – Tejus Prasad Dec 03 '15 at 11:33
1 Answers
1
Consider
m.mapValues { case(x,y) => x+y }
which creates a new Map
with same keys and computed values. 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
.
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; hence as a standard (intuitive) approach consider pattern-matching on the entire key-value group using map
for instance like this,
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)
-
Take a look at http://blog.bruchez.name/2013/02/mapmap-vs-mapmapvalues.html if using `mapValues` – Kevin Meredith Dec 03 '15 at 16:01