Kotlin Map firstNotNullOf()
Syntax & Examples
Syntax of Map.firstNotNullOf()
The syntax of Map.firstNotNullOf() extension function is:
fun <K, V, R : Any> Map<out K, V>.firstNotNullOf( transform: (Entry<K, V>) -> R? ): R
This firstNotNullOf() extension function of Map returns the first non-null value produced by transform function being applied to entries of this map in iteration order, or throws NoSuchElementException if no non-null value was produced.
✐ Examples
1 Get first non-null character value in the map
In this example,
- We create a map named
map1
containing key-value pairs(1, 'a'), (2, null), (3, 'c')
. - We then apply the
firstNotNullOf()
function onmap1
, using the transform function{ it.value }
to extract values. - As a result, the first non-null value in
map1
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map1 = mapOf(1 to 'a', 2 to null, 3 to 'c');
val result = map1.firstNotNullOf { it.value }
print(result);
}
Output
a
2 Get first non-null integer value in the map
In this example,
- We create a map named
map2
containing key-value pairs('a', 1), ('b', null), ('c', 3)
. - We then apply the
firstNotNullOf()
function onmap2
, using the transform function{ it.value }
to extract values. - As a result, the first non-null value in
map2
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map2 = mapOf('a' to 1, 'b' to null, 'c' to 3);
val result = map2.firstNotNullOf { it.value }
print(result);
}
Output
1
3 Get first non-null string value in the map
In this example,
- We create a map named
map3
containing key-value pairs(1, 'apple'), (2, null), (3, 'cherry')
. - We then apply the
firstNotNullOf()
function onmap3
, using the transform function{ it.value }
to extract values. - As a result, the first non-null value in
map3
is returned. - We print the result to standard output.
Kotlin Program
fun main(args: Array<String>) {
val map3 = mapOf(1 to "apple", 2 to null, 3 to "cherry");
val result = map3.firstNotNullOf { it.value }
print(result);
}
Output
apple
Summary
In this Kotlin tutorial, we learned about firstNotNullOf() extension function of Map: the syntax and few working examples with output and detailed explanation for each example.