Kotlin Tutorials

Kotlin Map filterTo()
Syntax & Examples

Syntax of Map.filterTo()

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

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

This filterTo() extension function of Map appends all entries matching the given predicate into the mutable map given as destination parameter.



✐ Examples

1 Filter and append entries to the mutable map (exclude 'b')

In this example,

  • We create a map named map1 containing pairs of numbers and characters.
  • We create a mutable map named destination1.
  • We apply the filterTo() function on map1, appending entries to destination1, excluding the entry where the value is equal to 'b'.
  • The resulting map contains the filtered entries.
  • 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 destination1 = mutableMapOf<Int, Char>()
    map1.filterTo(destination1) { (_, value) -> value != 'b' }
    println(destination1)
}

Output

{1=a, 3=c}

2 Filter and append entries to the mutable map (include 'a')

In this example,

  • We create a map named map2 containing pairs of characters and numbers.
  • We create a mutable map named destination2.
  • We apply the filterTo() function on map2, appending entries to destination2, including the entry with the key 'a'.
  • The resulting map contains the filtered entries.
  • 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 destination2 = mutableMapOf<Char, Int>()
    map2.filterTo(destination2) { (key, _) -> key != 'a' }
    println(destination2)
}

Output

{b=2, c=3}

3 Filter and append entries to the mutable map (even numbers)

In this example,

  • We create a map named map3 containing pairs of strings and numbers.
  • We create a mutable map named destination3.
  • We apply the filterTo() function on map3, appending entries to destination3, including only the entries with even-numbered values.
  • The resulting map contains the filtered entries.
  • 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 destination3 = mutableMapOf<String, Int>()
    map3.filterTo(destination3) { (_, value) -> value % 2 == 0 }
    println(destination3)
}

Output

{banana=6}

Summary

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