Home > front end >  Remove key from map kotlin
Remove key from map kotlin

Time:05-04

I have a map as follows

  val parentMap= mutableMapOf<String,String>()
    parentMap["key1"]="value1"
    parentMap["key2"]="value2"
    parentMap["key3"]="value3"

And I have a list of keys val keyList= listOf("key1","key3")

I want to remove the key from map which doesn't exist in my keylist

The current solution I am using is

val filteredMap= mutableMapOf<String,String>()
    keyList.forEach {
        if(parentMap.containsKey(it))
            filteredMap[it]=parentMap[it]!!
    }
    println(filteredMap)

Is there any more better way to do this?

CodePudding user response:

This can be achieved even a little shorter:

val map = mapOf(
     "key1" to "value1",
     "key2" to "value2",
     "key3" to "value3"
)
 
val list = listOf("key1")
 
val filteredMap = map.filterKeys(list::contains)

the result is: {key1=value1}

CodePudding user response:

You can do it much easier like this:

val filteredMap = parentMap.filter { keyList.contains(it.key) }
  • Related