Kotlin Map mapNotNull()
Syntax & Examples
Syntax of Map.mapNotNull()
The syntax of Map.mapNotNull() extension function is:
fun <K, V, R : Any> Map<out K, V>.mapNotNull( transform: (Entry<K, V>) -> R? ): List<R>
This mapNotNull() extension function of Map returns a list containing only the non-null results of applying the given transform function to each entry in the original map.
✐ Examples
1 Filter keys by even values and return non-null results
In this example,
- We create a map named
map1
with key-value pairs. - We use the
mapNotNull
function onmap1
, applying a transform function that returns the key if its corresponding value is even, otherwise null. - The non-null results are collected into a list.
- We print the resulting list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf("key1" to 1, "key2" to 2, "key3" to 3)
val result = map1.mapNotNull { (key, value) -> if (value % 2 == 0) key else null }
println(result)
}
Output
[key2]
2 Filter and return non-null values from the map
In this example,
- We create a map named
map2
with key-value pairs, including null values. - We use the
mapNotNull
function onmap2
, applying a transform function that returns the value if it is not null. - The non-null values are collected into a list.
- We print the resulting list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf("apple" to null, "banana" to 6, "cherry" to 7)
val result = map2.mapNotNull { (_, value) -> value }
println(result)
}
Output
[6, 7]
3 Return non-null values from the map
In this example,
- We create a map named
map3
with key-value pairs, including a null value. - We use the
mapNotNull
function onmap3
, applying a transform function that returns the value if it is not null. - The non-null values are collected into a list.
- We print the resulting list to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "one", 2 to "two", 3 to null)
val result = map3.mapNotNull { (_, value) -> value }
println(result)
}
Output
[one, two]
Summary
In this Kotlin tutorial, we learned about mapNotNull() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.