How to remove multiple keys from a Map dynamically

To remove multiple keys from a Map, use the -- method:

a -- Set("a", "r")

The following explains the type mismatch error.

The version of the - method on Map that you're calling takes three arguments: (1) the key of the first element to remove, (2) the key of the second element to remove, and (3) a varargs representating zero or more remaining elements to remove. (The other version of - takes a single key as the argument.)

a - ("a", "r")

The above code is not passing a tuple to the - method; it's passing two String arguments to the - method. In other words, the above is equivalent to:

a.-("a", "r")

However, the code below...

val keys = ("d", "r")
a - keys

...is trying to pass a tuple as an argument to the - method. It's equivalent to:

a.-(("d", "r"))

You get a type mismatch error when you try to pass a tuple to the - method, because the - method expects one or more Strings.


This is nice and concise.

scala> a - "a" - "r"
res0: scala.collection.immutable.Map[String,Int] = Map(d -> 4)

If you'd like to compose the list of keys before the removal.

val ks = Seq("d","r")
ks.foldLeft(a)(_ - _)  //res2: collection.immutable.Map[String,Int] = Map(a -> 2)

Tags:

Scala