Kotlin Tutorials

Kotlin Map filterNotTo()
Syntax & Examples

Syntax of Map.filterNotTo()

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

fun <K, V, M : MutableMap<in K, in V>> Map<out K, V>.filterNotTo( destination: M, predicate: (Entry<K, V>) -> Boolean ): M

This filterNotTo() extension function of Map appends all entries not matching the given predicate into the given destination.



✐ Examples

1 Filter out key 'b' 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 create an empty mutable map filteredMap1.
  • We use the filterNotTo() function on map1 to filter out key 'b' and append the remaining entries to filteredMap1.
  • The resulting filteredMap1 contains key-value pairs ('a' to 1), ('c' to 3).
  • 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 = mutableMapOf<Char, Int>()
    map1.filterNotTo(filteredMap1) { (key, value) -> key == 'b' }
    println(filteredMap1)
}

Output

{a=1, c=3}

2 Filter out keys 'a' and 'c' 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 create an empty mutable map filteredMap2.
  • We use the filterNotTo() function on map2 to filter out keys 'a' and 'c' and append the remaining entries to filteredMap2.
  • The resulting filteredMap2 contains key-value pairs ('b' to 2).
  • 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 = mutableMapOf<Char, Int>()
    map2.filterNotTo(filteredMap2) { (key, value) -> key == 'a' || key == 'c' }
    println(filteredMap2)
}

Output

{b=2}

3 Filter out keys with length greater than 5 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 create an empty mutable map filteredMap3.
  • We use the filterNotTo() function on map3 to filter out keys with length greater than 5 and append the remaining entries to filteredMap3.
  • The resulting filteredMap3 contains key-value pairs ('apple' to 1).
  • 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 = mutableMapOf<String, Int>()
    map3.filterNotTo(filteredMap3) { (key, value) -> key.length > 5 }
    println(filteredMap3)
}

Output

{apple=1}

Summary

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