Kotlin List.firstOrNull()
The Kotlin List.firstOrNull() function is used to retrieve the first element of a list or the first element satisfying a given predicate. If the list is empty or no element satisfies the predicate, it returns null
.
Syntax
List.firstOrNull()
Returns the first element, or null if the list is empty.
List.firstOrNull(predicate)
Returns the first element matching the given predicate, or null if element was not found.
The return type of firstOrNull() would be same as that of the returned element.
Example 1: Getting the first element of a list
In this example, we shall take an integer list, and get the first element of this list using List.firstOrNull(), without passing any predicate.
Program
fun main() {
val numbers = listOf(10, 20, 30, 40, 50)
val firstNumber = numbers.firstOrNull()
println(firstNumber)
}
Output
10
Example 2: Getting the first element that satisfies a condition
In this example, we shall take a list of strings, and get the first string element that starts with the character 'b'
, using List.first() function with the predicate.
Program
fun main() {
val fruits = listOf("apple", "banana", "cherry", "berry")
val firstBFruit = fruits.firstOrNull{ it.startsWith('b') }
println(firstBFruit)
}
Output
banana
Example 3: Using firstOrNull() with an empty list
In this example, we shall take an empty list of integers, and print the return value of firstOrNull() for this list.
Program
fun main() {
val emptyList = listOf<Int>()
val firstElement = emptyList.firstOrNull()
println(firstElement)
}
Output
null