0

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!

Soumyaansh
  • 8,626
  • 7
  • 45
  • 45
高源伯
  • 367
  • 4
  • 4

1 Answers1

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) 
Community
  • 1
  • 1
elm
  • 20,117
  • 14
  • 67
  • 113