In Scala, apply a function to values ​​for some keys in an immutable map

Let a fixed mapping

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)

set of keys of interest

val k = Set(0,2)

and functions

def f(i:Int) = i + 1

How to apply fto values ​​in a map displayed by keys of interest so that the resulting map is

Map(0 -> 1, 1 -> 10, 2 -> 21, 3 -> 30)
+4
source share
3 answers
m.transform{ (key, value) => if (k(key)) f(value) else value }
+6
source

This is the first thing that appeared in my head, but I'm sure that in Scala you could make it more beautiful:

m.map(e =>  {
    if(k.contains(e._1)) (e._1 -> f(e._2)) else (e._1 -> e._2)
})  
+1
source

@ Regis-jean-gilles answer option using mapand pattern matching

m.map { case a @ (key, value) => if (k(key)) key -> f(value) else a } 
0
source

Source: https://habr.com/ru/post/1537686/


All Articles