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.
In this example,
map1
containing pairs of numbers and characters.destination1
.filterTo()
function on map1
, appending entries to destination1
, excluding the entry where the value is equal to 'b'
.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)
}
{1=a, 3=c}
In this example,
map2
containing pairs of characters and numbers.destination2
.filterTo()
function on map2
, appending entries to destination2
, including the entry with the key 'a'
.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)
}
{b=2, c=3}
In this example,
map3
containing pairs of strings and numbers.destination3
.filterTo()
function on map3
, appending entries to destination3
, including only the entries with even-numbered values.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)
}
{banana=6}
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.