Kotlin Map filterKeys()
Syntax & Examples
Syntax of Map.filterKeys()
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.
✐ 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 use the
filterKeys()function onmap1with a predicate that filters out key 'b'. - The resulting map
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 = map1.filterKeys { it != 'b' }
println(filteredMap1)
}Output
{a=1, c=3}2 Filter 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 use the
filterKeys()function onmap2with a predicate that filters keys 'a' and 'c'. - The resulting map
filteredMap2contains key-value pairs('a' to 1), ('c' to 3). - 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 = map2.filterKeys { it == 'a' || it == 'c' }
println(filteredMap2)
}Output
{a=1, c=3}3 Filter 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 use the
filterKeys()function onmap3with a predicate that filters keys with length greater than 5. - The resulting map
filteredMap3contains key-value pairs('banana' to 2), ('cherry' to 3). - 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 = map3.filterKeys { it.length > 5 }
println(filteredMap3)
}Output
{banana=2, cherry=3}Summary
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.