0
0
KotlinHow-ToBeginner · 3 min read

How to Filter Map in Kotlin: Syntax and Examples

In Kotlin, you can filter a map using filter, filterKeys, or filterValues functions. These functions return a new map containing only entries that match the given condition in the lambda expression.
📐

Syntax

Kotlin provides three main functions to filter maps:

  • filter { (key, value) -> condition }: Filters entries by both key and value.
  • filterKeys { key -> condition }: Filters entries by key only.
  • filterValues { value -> condition }: Filters entries by value only.

Each returns a new Map with entries that satisfy the condition.

kotlin
val filteredMap = originalMap.filter { (key, value) -> /* condition */ }
val filteredByKey = originalMap.filterKeys { key -> /* condition */ }
val filteredByValue = originalMap.filterValues { value -> /* condition */ }
💻

Example

This example shows how to filter a map to keep only entries where the value is greater than 10, and also how to filter by keys starting with a specific letter.

kotlin
fun main() {
    val numbers = mapOf("a" to 5, "b" to 15, "c" to 25, "d" to 8)

    val filteredByValue = numbers.filterValues { it > 10 }
    println("Filtered by value > 10: $filteredByValue")

    val filteredByKey = numbers.filterKeys { it.startsWith("b") || it.startsWith("c") }
    println("Filtered by keys starting with 'b' or 'c': $filteredByKey")

    val filteredByEntry = numbers.filter { (key, value) -> key == "a" || value > 20 }
    println("Filtered by key 'a' or value > 20: $filteredByEntry")
}
Output
Filtered by value > 10: {b=15, c=25} Filtered by keys starting with 'b' or 'c': {b=15, c=25} Filtered by key 'a' or value > 20: {a=5, c=25}
⚠️

Common Pitfalls

One common mistake is trying to filter a map in place, but Kotlin's filter functions always return a new map and do not modify the original. Another is confusing filterKeys and filterValues with filter, which requires a pair of key and value.

Also, forgetting that the lambda for filter receives a Map.Entry destructured as (key, value) can cause errors.

kotlin
fun main() {
    val map = mapOf("x" to 1, "y" to 2)

    // Wrong: trying to modify original map (this won't change 'map')
    map.filterValues { it > 1 }
    println(map) // prints original map unchanged

    // Correct: assign the result to a new variable
    val filtered = map.filterValues { it > 1 }
    println(filtered) // prints filtered map

    // Wrong lambda parameter usage
    // map.filter { it > 1 } // Error: 'it' is Map.Entry, not Int

    // Correct usage
    val filteredCorrect = map.filter { (_, value) -> value > 1 }
    println(filteredCorrect)
}
Output
{x=1, y=2} {y=2} {y=2}
📊

Quick Reference

FunctionDescriptionLambda Parameter
filterFilters entries by key and value(key, value) -> Boolean
filterKeysFilters entries by key onlykey -> Boolean
filterValuesFilters entries by value onlyvalue -> Boolean

Key Takeaways

Use filter, filterKeys, or filterValues to create a new filtered map based on conditions.
filter takes a lambda with both key and value, while filterKeys and filterValues take only key or value respectively.
Filtering does not change the original map; always use the returned filtered map.
Destructure Map.Entry as (key, value) in filter lambdas to access both parts easily.
Remember to assign the result of filtering to a variable to keep the filtered map.