This article explores different ways to filter a map in Kotlin.

A simple solution is to use a for loop to iterate over the map and filter it based on key or value using a conditional statement. For instance, the following code example filters the keys starting with B.

Download Code

Output:

{Blue=#0000FF, Black=#000000}

 
You can also iterate a map with the forEach() function and perform a check on each key of the map.

Download Code

Output:

{Blue=#0000FF, Black=#000000}

 
Another solution is to in-place filter the map. However, it is not permissible to modify the map while iterating over it; otherwise, java.util.ConcurrentModificationException will be thrown. To avoid concurrent modification exception, you can iterate over the copy of the map and remove keys from the original map.

Download Code

Output:

{Blue=#0000FF, Black=#000000}

That’s all about filtering a map in Kotlin.