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
CodePudding user response:
Convert the list of keys to a Set
and then use filterKeys
to select all keys that are not in that set:
val kSet = keys.toSet
map.filterKeys(!kSet.contains(_))
CodePudding user response:
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