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")
We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.
Scala Map remove() method with exampleThe remove() method is utilized to remove a key from the map and return its value only. Return Type: It returns the value of the key present in the above method as argument. We use mutable map here, as remove method is a member of mutable map.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With