Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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")  
like image 207
Govind Singh Avatar asked Feb 22 '14 14:02

Govind Singh


People also ask

How do I add a key-value pair to a Scala map?

We can insert new key-value pairs in a mutable map using += operator followed by new pairs to be added or updated.

How do you delete a Scala?

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.


3 Answers

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.

like image 131
Leo Avatar answered Oct 07 '22 16:10

Leo


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")
like image 36
Kevin Wright Avatar answered Oct 07 '22 14:10

Kevin Wright


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.

like image 11
Sudeep Juvekar Avatar answered Oct 07 '22 15:10

Sudeep Juvekar