Map both keys and values of a Scala Map
Solution 1:
map
method iterates though all (key, value)
pairs. You can use it like this:
val m = Map("a" -> 1, "b" -> 2)
val incM = m map {case (key, value) => (key, value + 1)}
Solution 2:
What about this code:
val m = Map(1 -> "one", 2 -> "two")
def f(k: Int, v: String) = k + "-" + v
m map {case (k, v) => (k, f(k, v))}
Which produces:
Map(1 -> 1-one, 2 -> 2-two)
This can be packaged into utility method:
def mapKeysAndValues[A,B,C](input: Map[A,B], fun: (A, B) => C) =
input map {case(k,v) => (k, fun(k, v))}
Usage:
mapKeysAndValues(
Map(1 -> "one", 2 -> "two"),
(k: Int, v: String) => k + "-" + v
)
Solution 3:
m map (t => (t._1, t._2 + 1))
m map (t => t._1 -> t._2 + 1)
Solution 4:
With some Scalaz:
scala> def fst[A, B] = (x: (A, B)) => x._1
fst: [A, B]=> (A, B) => A
scala> Map(1 -> "Lorem", 2 -> "Ipsum").map(fst &&& Function.tupled(_.toString + _))
res1: scala.collection.immutable.Map[Int,java.lang.String] = Map(1 -> 1Lorem, 2 -> 2Ipsum)
I like @tenshi's solution better.