Kotlin List mapNotNull()
Syntax & Examples
Syntax of List.mapNotNull()
The syntax of List.mapNotNull() extension function is:
fun <T, R : Any> Iterable<T>.mapNotNull( transform: (T) -> R? ): List<R>
This mapNotNull() extension function of List returns a list containing only the non-null results of applying the given transform function to each element in the original collection.
✐ Examples
1 Example
In this example,
- We create a list named
list1
containing the integers1, 2, 3
. - We then apply the
mapNotNull
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we check if the element is even. If it is, we return the element multiplied by 2; otherwise, we return
null
. - The
mapNotNull
function returns a new list containing only the non-null results. - The resulting list, containing doubled values of even numbers, is stored in
result
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf(1, 2, 3, 4);
val result = list1.mapNotNull { if (it % 2 == 0) it * 2 else null }
print(result);
}
Output
[4, 8]
2 Example
In this example,
- We create a list named
list1
containing the characters'a', 'b', 'c'
. - We then apply the
mapNotNull
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we check if the element is equal to
'b'
. If it is, we return the element; otherwise, we returnnull
. - The
mapNotNull
function returns a new list containing only the non-null results. - The resulting list, containing only the element
'b'
, is stored inresult
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c");
val result = list1.mapNotNull { if (it == "b") it else null }
print(result);
}
Output
[b]
3 Example
In this example,
- We create a list named
list1
containing the strings'apple', 'banana', 'cherry'
. - We then apply the
mapNotNull
function tolist1
, which takes a lambda with one parameter:it
. - Within the lambda, we check if the length of the string is greater than 5. If it is, we return the element; otherwise, we return
null
. - The
mapNotNull
function returns a new list containing only the non-null results. - The resulting list, containing strings with a length greater than 5, is stored in
result
. - Finally, we print the value of
result
to standard output.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry");
val result = list1.mapNotNull { if (it.length > 5) it else null }
print(result);
}
Output
[banana, cherry]
Summary
In this Kotlin tutorial, we learned about mapNotNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.