Kotlin Map filterNot()
Syntax & Examples
Syntax of Map.filterNot()
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.
✐ Examples
1 Filter out map entries by value ('b')
In this example,
- We create a map named
map1
containing pairs of numbers and characters. - We apply the
filterNot()
function onmap1
to exclude the entries where the value is equal to'b'
. - The resulting map contains the entries excluding the one with the value
'b'
. - 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 filteredMap1 = map1.filterNot { (_, value) -> value == 'b' }
println(filteredMap1)
}
Output
{1=a, 3=c}
2 Filter out map entries by key (include 'a')
In this example,
- We create a map named
map2
containing pairs of characters and numbers. - We apply the
filterNot()
function onmap2
to exclude the entries where the key is not equal to'a'
. - The resulting map contains the entry with the key
'a'
and its corresponding value. - 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 filteredMap2 = map2.filterNot { (key, _) -> key != 'a' }
println(filteredMap2)
}
Output
{a=1}
3 Filter out map entries by value (odd numbers)
In this example,
- We create a map named
map3
containing pairs of strings and numbers. - We apply the
filterNot()
function onmap3
to exclude the entries where the value is an odd number. - The resulting map contains the entries with even-numbered values.
- 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 filteredMap3 = map3.filterNot { (_, value) -> value % 2 == 0 }
println(filteredMap3)
}
Output
{apple=5, cherry=7}
Summary
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.