scaladictionarycollectionsscala-collections

How to remove key value from map when keys are store in list in scala


I have list of keys and map following:

val keys = List("key1", "key2", "key5")

Map("key1" -> 1, "key2" -> 2, "key3" ->3, "key4" -> 4, "key5" -> 5)

I want to remove all of the keys that are in keys list.

I know I can iterator through keys list and check if map contains the key and if it does I can remove it.

Is there any easier way to do this without iterating keys list in which I just provide list of keys and all of keys that are presented in list are filtered out from map?

Thank you


Solution

  • you can use -- method

    val keys = List("key1", "key2", "key5")
    val map = Map("key1" -> 1, "key2" -> 2, "key3" ->3, "key4" -> 4, "key5" -> 5)
    map -- keys