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")
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")
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
.
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")
That depends on the type of Scala.collection Map you are using. Scala comes with both mutable
and immutable
Maps. Checks these links:
http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.immutable.Map
and
http://www.scala-lang.org/api/2.10.2/index.html#scala.collection.mutable.Map
In both types of maps, -
is usually the operation to remove a key. The details depend on the type of map. A mutable
map can be modified in place by using -=
. Something like
if (m.contains("privacy") && m.getOrElse("privacy", 1) == 0) {
m -= "play"
}
On the other hand, an immutable map can not be modified in place and has to return a new map after removing an element.
if (m.contains("privacy") && m.getOrElse("privacy", 1) == 0) {
val newM = m - "play"
}
Notice that you are creating a new immutable map.
val m = Map("data" -> "sumi", "rel" -> 2, "privacy" -> 0,"status" -> 1,"name"->"govind singh")
scala> if(m("privacy")==0) m.filterKeys(_ != "data")
res63: Any = Map(name -> govind singh, rel -> 2, privacy -> 0, status -> 1)