Reputation: 20415
Let an immutable map
val m = (0 to 3).map {x => (x,x*10) }.toMap
m: scala.collection.immutable.Map[Int,Int] = Map(0 -> 0, 1 -> 10, 2 -> 20, 3 -> 30)
a collection of keys of interest
val k = Set(0,2)
and a function
def f(i:Int) = i + 1
How to apply f
onto the values in the map mapped by the keys of interest so that the resulting map would be
Map(0 -> 1, 1 -> 10, 2 -> 21, 3 -> 30)
Upvotes: 4
Views: 2815
Reputation: 1705
A variation of @regis-jean-gilles answer using map
and pattern matching
m.map { case a @ (key, value) => if (k(key)) key -> f(value) else a }
Upvotes: 0
Reputation: 32719
m.transform{ (key, value) => if (k(key)) f(value) else value }
Upvotes: 6
Reputation: 1265
That's the first thing that popped into my mind but I am pretty sure that in Scala you could do it prettier:
m.map(e => {
if(k.contains(e._1)) (e._1 -> f(e._2)) else (e._1 -> e._2)
})
Upvotes: 1