The indexOfFirst()
method will return the index of the first element of the ArrayList
that satisfies the provided -1
is returned.
inline fun <T> List<T>.indexOfFirst(
predicate: (T) -> Boolean
): Int
This method takes a predicate function as an argument.
This method returns an integer value denoting the index of the first element from the list that satisfies the provided predicate.
If no element matches, then -1
is returned.
The method below demonstrates how to use the indexOfFirst()
method.
fun main() {var list = ArrayList<Int>()list.add(1)list.add(2)list.add(3)println("The ArrayList is $list")var firstIndex = list.indexOfFirst({it % 2 == 0 })println("\nThe first index of even element is $firstIndex")firstIndex = list.indexOfFirst({it > 4})println("\nThe first index of elemen > 4 is $firstIndex")}
In the above code, we see the following:
Lines 3-6: We create a new ArrayList
with the name list
and add three elements to the list
using the add()
method. The list is [1,2,3]
.
Line 9: We use the indexOfFirst()
method with a predicate function as an argument. This function will return true
if the element is even. The indexOfFirst()
method will loop through all elements of the ArrayList
.
0
, the element present is 1
, which is not even, so the predicate function returns false
.1
, the element present is 2
, which is even, so the predicate function returns true
. Due to this, the index of element 2
will be returned as a result of the indexOfFirst()
method.Line 12: We use the indexOfFirst()
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 -1
will be returned.