how to remove key value from map in scala

Govind Singh picture Govind Singh · Feb 22, 2014 · Viewed 41.5k times · Source
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")  

Answer

Leo picture Leo · Feb 22, 2014

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.