The firstOrNull()
method can be used in two ways.
ArrayList
. If the ArrayList
is empty, then null
is returned.ArrayList
that satisfies the provided null
is returned.// to get first element
fun <T> List<T>.firstOrNull(): T?
This method doesn’t take any argument.
Returns the first element if the ArrayList
is not empty. Otherwise, null
is returned.
fun <T> List<T>.firstOrNull(
predicate: (T) -> Boolean
): T?
This method takes a predicate function as an argument.
This method returns the first element from the list that satisfies the provided the predicate.
If no element matches the given predicate function, then null
is returned.
The method below demonstrates how to use the firstOrNull()
method.
fun main() { var list = ArrayList<Int>() println("The ArrayList is $list") var firstEle = list.firstOrNull(); println("The First element is $firstEle"); list.add(1) list.add(2) list.add(3) list.add(4) println("\nThe ArrayList is $list") firstEle = list.firstOrNull(); println("The First element is $firstEle"); firstEle = list.firstOrNull({it % 2 == 0 }) println("\nThe first even element is $firstEle") firstEle = list.firstOrNull({it > 4}) println("\nThe firstEle element > 4 is $firstEle") }
In the above code, we see the following:
Line 3: We create a new ArrayList
with the name list
. The list contains no element []
.
Line 5: We use the firstOrNull
method to get the first element of the list. In our case, the list
is empty, so null
is returned.
Lines 8-11: We add four elements to the list
using the add
method. Now the list is [1,2,3,4]
.
Line 13: We use the firstOrNull
method to get the list’s first element(1
). The list is not empty, so the first element of the list
is returned.
Line 16: We use the firstOrNull
method with a predicate function as an argument. This function will return true
if the element is even. The firstOrNull
method will return the first even element of the list
. In our case, 2
will be returned.
Line 19: We use the firstOrNull
method with a predicate function as an argument. This function will return true
if the element is greater than 4
. In our ArrayList
, there is no element that is greater than 4
, so null
will be returned.
RELATED TAGS
CONTRIBUTOR
View all Courses