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 ): MThis 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
map1with key-value pairs('a' to 1), ('b' to 2), ('c' to 3). - We create an empty mutable map
filteredMap1. - We use the
filterNotTo()function onmap1to filter out key 'b' and append the remaining entries tofilteredMap1. - The resulting
filteredMap1contains key-value pairs('a' to 1), ('c' to 3). - We print
filteredMap1to 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
map2with key-value pairs('a' to 1), ('b' to 2), ('c' to 3). - We create an empty mutable map
filteredMap2. - We use the
filterNotTo()function onmap2to filter out keys 'a' and 'c' and append the remaining entries tofilteredMap2. - The resulting
filteredMap2contains key-value pairs('b' to 2). - We print
filteredMap2to 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
map3with key-value pairs('apple' to 1), ('banana' to 2), ('cherry' to 3). - We create an empty mutable map
filteredMap3. - We use the
filterNotTo()function onmap3to filter out keys with length greater than 5 and append the remaining entries tofilteredMap3. - The resulting
filteredMap3contains key-value pairs('apple' to 1). - We print
filteredMap3to 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.