The syntax of Map.filterKeys() extension function is:
fun <K, V> Map<out K, V>.filterKeys( predicate: (K) -> Boolean ): Map<K, V>
This filterKeys() extension function of Map returns a map containing all key-value pairs with keys matching the given predicate.
In this example,
map1
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.filterKeys()
function on map1
with a predicate that filters out key 'b'.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 = map1.filterKeys { it != 'b' }
println(filteredMap1)
}
{a=1, c=3}
In this example,
map2
with key-value pairs ('a' to 1), ('b' to 2), ('c' to 3)
.filterKeys()
function on map2
with a predicate that filters keys 'a' and 'c'.filteredMap2
contains key-value pairs ('a' to 1), ('c' to 3)
.filteredMap2
to standard output.fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to 2, 'c' to 3)
val filteredMap2 = map2.filterKeys { it == 'a' || it == 'c' }
println(filteredMap2)
}
{a=1, c=3}
In this example,
map3
with key-value pairs ('apple' to 1), ('banana' to 2), ('cherry' to 3)
.filterKeys()
function on map3
with a predicate that filters keys with length greater than 5.filteredMap3
contains key-value pairs ('banana' to 2), ('cherry' to 3)
.filteredMap3
to standard output.fun main(args: Array<String>) {
val map3 = mapOf("apple" to 1, "banana" to 2, "cherry" to 3)
val filteredMap3 = map3.filterKeys { it.length > 5 }
println(filteredMap3)
}
{banana=2, cherry=3}
In this Kotlin tutorial, we learned about filterKeys() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.