1, "key2" -> 2, "key3" ->3, "key4" -> 4, "key5" -> 5) I w" /> 1, "key2" -> 2, "key3" ->3, "key4" -> 4, "key5" -> 5) I w" /> 1, "key2" -> 2, "key3" ->3, "key4" -> 4, "key5" -> 5) I w"/>

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

314 views Asked by At

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

2

There are 2 answers

0
basdanny On BEST ANSWER

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
1
Tim On

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(_))