47
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")  
Govind Singh
  • 15,282
  • 14
  • 72
  • 106

4 Answers4

68

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.

Leo
  • 37,640
  • 8
  • 75
  • 100
  • You don't have to use pattern matching here because if there is no key which you are removing from existing Map it returns the same Map. No errors. – Arpit Suthar Sep 22 '16 at 07:27
26

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")
Kevin Wright
  • 49,540
  • 9
  • 105
  • 155
  • This retains reference to the filtering collection not allowing it to be garbage collected. – St.Antario Jun 21 '18 at 13:15
  • 1
    Building off of @St.Antario's comment, `filterKeys` results in a map that cannot be serialized. So, if you are filtering a map that you plan on using as a Spark `Broadcast`, this approach will not work. In these cases, you are better off with something like the following: `valuesToRemove.foldLeft(theMap) { (filteredMap, valueToRemove) => filteredMap - valueToRemove }` – Cities Nov 08 '18 at 19:48
11

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.

Sudeep Juvekar
  • 4,898
  • 3
  • 29
  • 35
0
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)
RAGHHURAAMM
  • 1,099
  • 7
  • 15