Kotlin Tutorials

Kotlin Map filter()
Syntax & Examples

Syntax of Map.filter()

The syntax of Map.filter() extension function is:

fun <K, V> Map<out K, V>.filter( predicate: (Entry<K, V>) -> Boolean ): Map<K, V>

This filter() extension function of Map returns a new map containing all key-value pairs matching the given predicate.



✐ Examples

1 Filter map entries by value ('b')

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We apply the filter() function on map1 to retain only the entries where the value is equal to 'b'.
  • The resulting filtered map contains the entry with the key 2 and value 'b'.
  • We print the filtered map to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
    val filteredMap1 = map1.filter { (_, value) -> value == 'b' }
    println(filteredMap1)
}

Output

{2=b}

2 Filter map entries by key (exclude 'a')

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We apply the filter() function on map2 to exclude the entry with the key 'a'.
  • The resulting filtered map contains entries excluding the key 'a'.
  • We print the filtered map to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
    val filteredMap2 = map2.filter { (key, _) -> key != 'a' }
    println(filteredMap2)
}

Output

{b=2, c=3}

3 Filter map entries by value (even numbers)

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We apply the filter() function on map3 to retain only the entries where the value is an even number.
  • The resulting filtered map contains the entries with even-numbered values.
  • We print the filtered map to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
    val filteredMap3 = map3.filter { (_, value) -> value % 2 == 0 }
    println(filteredMap3)
}

Output

{banana=6}

Summary

In this Kotlin tutorial, we learned about filter() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.