Kotlin Tutorials

Kotlin Map filterValues()
Syntax & Examples

Syntax of Map.filterValues()

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

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

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



✐ Examples

1 Filter out even numbers from the map

In this example,

  • We create a map named map1 with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3).
  • We use the filterValues() function on map1 to filter even numbers and create filteredMap1.
  • filteredMap1 contains key-value pairs ('b' to 2).
  • We print filteredMap1 to standard output.

Kotlin Program

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

Output

{b=2}

2 Filter out values less than 2 from the map

In this example,

  • We create a map named map2 with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3).
  • We use the filterValues() function on map2 to filter values less than 2 and create filteredMap2.
  • filteredMap2 contains key-value pairs ('b' to 2), ('c' to 3).
  • We print filteredMap2 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.filterValues { value -> value > 1 }
    println(filteredMap2)
}

Output

{b=2, c=3}

3 Filter out odd numbers from the map

In this example,

  • We create a map named map3 with key-value pairs ('apple' to 1), ('banana' to 2), ('cherry' to 3).
  • We use the filterValues() function on map3 to filter odd numbers and create filteredMap3.
  • filteredMap3 contains key-value pairs (apple=1), (cherry=3).
  • We print filteredMap3 to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
    val filteredMap3 = map3.filterValues { value -> value % 2 != 0 }
    println(filteredMap3)
}

Output

{apple=1, cherry=3}

Summary

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