Kotlin List – Find the Last Occurrence of an Element
To find the last occurrence of a given element in this List in Kotlin, call lastIndexOf()
function on this List object and pass the element, whose index we want, as argument to this function.
The Kotlin List.lastIndexOf() function returns the index of the last occurrence of the specified element in the list.
There could be multiple occurrences of any element in a list. But using List.lastIndexOf() function, we can get the last occurrence of the item in a list.
Syntax of List.lastIndexOf()
The syntax of List.lastIndexOf() function is
list.lastIndexOf(element)
Parameter | Description |
---|---|
element | Required. The element whose last occurrence in the list has to be found out. |
Return Value
List.lastIndexOf() function returns the index of the last occurrence of the specified element in the list. If the specified element is not present in the list, then the function returns -1.
Example 1: Get Index of Last Occurrence of Element
In this example, we will take a list of elements (say strings). We will then find the last index of element "bc"
in the list using List.lastIndexOf() function.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "bc", "de")
val element = "bc"
val index = list1.lastIndexOf(element)
print("The index of last occurrence of element is : $index")
}
Output
The index of last occurrence of element is : 3
Example 2: List.lastIndexOf() – Element not in the List
In this example, we will try to find the output of List.lastIndexOf() function, when the element is not present in the list.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("ab", "bc", "cd", "bc", "de")
val element = "mm"
val index = list1.lastIndexOf(element)
print("The index of last occurrence of element is : $index")
}
Output
The index of last occurrence of element is : -1
Conclusion
In this Kotlin Tutorial, we learned how to get the index of last occurrence of specific element in a given list, using Kotlin List.lastIndexOf() function.