How to use the firstOrNull() method of ArrayList in Kotlin
Overview
The firstOrNull() method can be used in two ways.
- To get the first element of the
ArrayList. If theArrayListis empty, thennullis returned. - To get the first element of the
ArrayListthat satisfies the provided . If no element matches the provided predicate function, thenpredicate function Predicate is a Functional interface, which takes one argument and returns either true or false based on the condition defined nullis returned.
Syntax to get the first element
// to get first element
fun <T> List<T>.firstOrNull(): T?
Parameter
This method doesn’t take any argument.
Return value
Returns the first element if the ArrayList is not empty. Otherwise, null is returned.
Syntax to get the first element that matches the predicate
fun <T> List<T>.firstOrNull(
predicate: (T) -> Boolean
): T?
Parameter
This method takes a predicate function as an argument.
Return value
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.
Code
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")}
Explanation
In the above code, we see the following:
-
Line 3: We create a new
ArrayListwith the namelist. The list contains no element[]. -
Line 5: We use the
firstOrNullmethod to get the first element of the list. In our case, thelistis empty, sonullis returned. -
Lines 8-11: We add four elements to the
listusing theaddmethod. Now the list is[1,2,3,4]. -
Line 13: We use the
firstOrNullmethod to get the list’s first element(1). The list is not empty, so the first element of thelistis returned. -
Line 16: We use the
firstOrNullmethod with a predicate function as an argument. This function will returntrueif the element is even. ThefirstOrNullmethod will return the first even element of thelist. In our case,2will be returned. -
Line 19: We use the
firstOrNullmethod with a predicate function as an argument. This function will returntrueif the element is greater than4. In ourArrayList, there is no element that is greater than4, sonullwill be returned.