The indexOfLast()
method returns the index of the last element of the ArrayList
that satisfies the provided -1
is returned.
inline fun <T> List<T>.indexOfLast(
predicate: (T) -> Boolean
): Int
This method takes a Predicate function as an argument.
This method returns an integer value, which denotes the last element index from the list that satisfies the provided Predicate.
If no element matches the given Predicate function, then -1
is returned.
The code written below demonstrates how we can use the indexOfLast()
method:
fun main() { var list = ArrayList<Int>() list.add(1) list.add(2) list.add(3) list.add(4) println("The ArrayList is $list") var lastIndex = list.indexOfLast({it % 2 == 0 }) println("\nThe last index of even element is $lastIndex") lastIndex = list.indexOfLast({it > 4}) println("\nThe last index of element > 4 is $lastIndex") }
Lines 3–7: We create a new ArrayList with the name list
and add four elements to the list
, using the add
method. The list is now [1,2,3,4]
.
Line 10: We use the indexOfLast()
method with a Predicate function as an argument. This function returns True
if the element is even. The indexOfLast()
method returns the index of the last even element. In our case, the value 3
is returned.
Line 13: We use the indexOfLast
method with a Predicate function as an argument. This function returns True
if the element is greater than 4
. In our ArrayList
, no element is greater than 4
. Hence, the value -1
is returned.
RELATED TAGS
CONTRIBUTOR
View all Courses