'Remove key from map kotlin
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?
Solution 1:[1]
You can do it much easier like this:
val filteredMap = parentMap.filter { keyList.contains(it.key) }
Solution 2:[2]
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}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ivo Beckers |
| Solution 2 | darth jemico |
