How to replace value in map for a key based on a condition in scala

10.4k Views Asked by At

I have several immutable map records like :

val map = Map("number"->7,"name"->"Jane","city"->"New York")

I need to identify the "name" key for each record and check its value.If value is "Jane" , I need to replace with "Doe" and update the map record.

2

There are 2 best solutions below

0
On

This can be achieved by a simple map operation and pattern matching.

scala> val dictionary = Map("number"->7,"name"->"Jane","city"->"New York")
map: scala.collection.immutable.Map[String,Any] = Map(number -> 7, name -> Jane, city -> New York)

scala> dictionary map {
     |   case ("name","Jane") => "name" -> "Doe"
     |   case x => x
     | }
res3: scala.collection.immutable.Map[String,Any] = Map(number -> 7, name -> Doe, city -> New York)
0
On

A simple if else logic should do the trick

map.map(k => {
  if(k._1.toString.equalsIgnoreCase("name") && k._2.toString.equalsIgnoreCase("jane"))
    (k._1, "Doe")
  else
    k
})

Or a simple match case should do the trick as well as explained by @rogue-one

map.map(k => (k._1.toString, k._2.toString) match{
  case ("name", "Jane") => k._1 -> "Doe"
  case _ => k
})

Thanks