Changing the values in a map

2,631 views
Skip to first unread message

John

unread,
Mar 26, 2012, 4:20:16 PM3/26/12
to scala-user
I'm trying to iterate over a map, changing the values of various keys
only if they meet certain conditions. Say I've got this map:

val m1 = Map[String, Int]("x"->0, "y"->20)

If I want to update EVERY value, this is fairly straightforward. For
example, if I want to add 1 to each entry, I could do this:

m1.mapValues(_ + 1)
and my output is Map(1, 21)

But what if I want to update only positive values? What if I want to
add 1 only to values > 0 so that my output is Map(0, 21)?

How do I do that? I need a way to retrieve the value of each key, make
a Boolean evaluation, and then conditionally apply my function. I
can't figure out how to do this. Can somebody help?

Thanks, John

Michael Schmitz

unread,
Mar 26, 2012, 4:25:50 PM3/26/12
to John, scala-user
You can add the check in your mapValues. If the check fails, map the
value to itself. Otherwise, map it to the new value.

m.mapValues { value =>
if (condition(value)) change(value)
else value

√iktor Ҡlang

unread,
Mar 26, 2012, 5:56:35 PM3/26/12
to Michael Schmitz, John, scala-user
scala> val m1 = Map[String, Int]("x"->0, "y"->20)
m1: scala.collection.immutable.Map[String,Int] = Map(x -> 0, y -> 20)

scala> m1.mapValues {
     |   case 0 => 5
     |   case x => x
     | }
res8: scala.collection.immutable.Map[String,Int] = Map(x -> 5, y -> 20)
--
Viktor Klang

Akka Tech Lead
Typesafe - The software stack for applications that scale

Twitter: @viktorklang

John

unread,
Mar 26, 2012, 8:03:12 PM3/26/12
to scala-user
Got it. Thanks to both of you!
Reply all
Reply to author
Forward
0 new messages