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