Filter a map in Kotlin
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val htmlColorCodes: MutableMap<String, String> = mutableMapOf(Pair("White", "#FFFFFF"), Pair("Silver", "#C0C0C0"), Pair("Blue", "#0000FF"), Pair("Olive", "#808000"), Pair("Black", "#000000")) val filteredMap = mutableMapOf<String, String>() for ((key, value) in htmlColorCodes) { if (key.startsWith("B")) { filteredMap[key] = value } } println(filteredMap) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main() { val htmlColorCodes: MutableMap<String, String> = mutableMapOf(Pair("White", "#FFFFFF"), Pair("Silver", "#C0C0C0"), Pair("Blue", "#0000FF"), Pair("Olive", "#808000"), Pair("Brown", "#000000")) val filteredMap = mutableMapOf<String, String>() htmlColorCodes.forEach { (key, value) -> if (key.startsWith("B")) { filteredMap[key] = value } } println(filteredMap) } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun main() { val htmlColorCodes: MutableMap<String, String> = mutableMapOf(Pair("White", "#FFFFFF"), Pair("Silver", "#C0C0C0"), Pair("Blue", "#0000FF"), Pair("Olive", "#808000"), Pair("Brown", "#000000")) htmlColorCodes.toMutableMap().map { (key, value) -> if (!key.startsWith("B")) { htmlColorCodes.remove(key) } } println(htmlColorCodes) } |
Output:
{Blue=#0000FF, Black=#000000}
That’s all about filtering a map in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)