Kotlin Map filterValues()
Syntax & Examples
Syntax of Map.filterValues()
The syntax of Map.filterValues() extension function is:
fun <K, V> Map<out K, V>.filterValues( predicate: (V) -> Boolean ): Map<K, V>This filterValues() extension function of Map returns a map containing all key-value pairs with values matching the given predicate.
✐ Examples
1 Filter out even numbers 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
filterValues()function onmap1to filter even numbers and createfilteredMap1. filteredMap1contains key-value pairs('b' to 2).- 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.filterValues { value -> value % 2 == 0 }
println(filteredMap1)
}Output
{b=2}2 Filter out values less than 2 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
filterValues()function onmap2to filter values less than 2 and createfilteredMap2. filteredMap2contains key-value pairs('b' to 2), ('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.filterValues { value -> value > 1 }
println(filteredMap2)
}Output
{b=2, c=3}3 Filter out odd numbers 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
filterValues()function onmap3to filter odd numbers and createfilteredMap3. filteredMap3contains key-value pairs(apple=1),(cherry=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.filterValues { value -> value % 2 != 0 }
println(filteredMap3)
}Output
{apple=1, cherry=3}Summary
In this Kotlin tutorial, we learned about filterValues() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.