how to remove key value from map in scala
Map(data -> "sumi", rel -> 2, privacy -> 0, status -> 1,name->"govind singh")
how to remove data from this map , if privacy is 0.
Map(rel -> 2, privacy -> 0, status -> 1,name->"govind singh")
Solution 1:
If you use immutable maps, you can use the -
method to create a new map without the given key:
val mx = Map("data" -> "sumi", "rel" -> 2, "privacy" -> 0)
val m = mx("privacy") match {
case 0 => mx - "data"
case _ => mx
}
=> m: scala.collection.immutable.Map[String,Any] = Map(rel -> 2, privacy -> 0)
If you use mutable maps, you can just remove a key with either -=
or remove
.
Solution 2:
If you're looking to scale this up and remove multiple members, then filterKeys
is your best bet:
val a = Map(
"data" -> "sumi",
"rel" -> "2",
"privacy" -> "0",
"status" -> "1",
"name" -> "govind singh"
)
val b = a.filterKeys(_ != "data")