Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

You can do it much easier like this:

val filteredMap = parentMap.filter { keyList.contains(it.key) }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading