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.
In this example,
map1
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.filteredMap1
.filterNotTo()
function on map1
to filter out key 'b' and append the remaining entries to filteredMap1
.filteredMap1
contains key-value pairs ('a' to 1), ('c' to 3)
.filteredMap1
to standard output.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)
}
{a=1, c=3}
In this example,
map2
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.filteredMap2
.filterNotTo()
function on map2
to filter out keys 'a' and 'c' and append the remaining entries to filteredMap2
.filteredMap2
contains key-value pairs ('b' to 2)
.filteredMap2
to standard output.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)
}
{b=2}
In this example,
map3
with key-value pairs ('apple' to 1), ('banana' to 2), ('cherry' to 3)
.filteredMap3
.filterNotTo()
function on map3
to filter out keys with length greater than 5 and append the remaining entries to filteredMap3
.filteredMap3
contains key-value pairs ('apple' to 1)
.filteredMap3
to standard output.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)
}
{apple=1}
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.