Kotlin List firstOrNull()
Syntax & Examples
Syntax of List.firstOrNull()
There are 2 variations for the syntax of List.firstOrNull() extension function. They are:
1.
fun <T> List<T>.firstOrNull(): T?This extension function returns the first element, or null if the list is empty.
2.
fun <T> Iterable<T>.firstOrNull( predicate: (T) -> Boolean ): T?This extension function returns the first element matching the given predicate, or null if element was not found.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing strings. - We use the
firstOrNullfunction onlist1to get the first element or null if the list is empty. - The first element of
list1is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("apple", "banana", "cherry")
val result = list1.firstOrNull()
println(result)
}Output
apple
2 Example
In this example,
- We create a list named
list2containing integers. - We use the
firstOrNullfunction onlist2with a predicate that checks if an element is greater than 10. - Since there is no element of
list2that satisfies the predicate, null is returned and stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf(1, 2, 3, 4, 5)
val result = list2.firstOrNull { it > 10 }
println(result)
}Output
null
3 Example
In this example,
- We create a list named
list3containing strings. - We use the
firstOrNullfunction onlist3with a predicate that checks if a string's length is greater than 5. - The first element of
list3that satisfies the predicate is stored inresult. - Finally, we print the value of
resultto standard output using theprintlnstatement.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("hello", "world")
val result = list3.firstOrNull { it.length > 5 }
println(result)
}Output
hello
Summary
In this Kotlin tutorial, we learned about firstOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.