The syntax of Map.filterNot() extension function is:
fun <K, V> Map<out K, V>.filterNot( predicate: (Entry<K, V>) -> Boolean ): Map<K, V>
This filterNot() extension function of Map returns a new map containing all key-value pairs not matching the given predicate.
In this example,
map1
containing pairs of numbers and characters.filterNot()
function on map1
to exclude the entries where the value is equal to 'b'
.'b'
.fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to 'b', 3 to 'c')
val filteredMap1 = map1.filterNot { (_, value) -> value == 'b' }
println(filteredMap1)
}
{1=a, 3=c}
In this example,
map2
containing pairs of characters and numbers.filterNot()
function on map2
to exclude the entries where the key is not equal to 'a'
.'a'
and its corresponding value.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val filteredMap2 = map2.filterNot { (key, _) -> key != 'a' }
println(filteredMap2)
}
{a=1}
In this example,
map3
containing pairs of strings and numbers.filterNot()
function on map3
to exclude the entries where the value is an odd number.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 5, "banana" to 6, "cherry" to 7)
val filteredMap3 = map3.filterNot { (_, value) -> value % 2 == 0 }
println(filteredMap3)
}
{apple=5, cherry=7}
In this Kotlin tutorial, we learned about filterNot() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.