Kotlin List lastIndexOf()
Syntax & Examples
Syntax of List.lastIndexOf()
The syntax of List.lastIndexOf() function is:
abstract fun lastIndexOf(element: E): IntThis lastIndexOf() function of List returns the index of the last occurrence of the specified element in the list, or -1 if the specified element is not contained in the list.
✐ Examples
1 Example
In this example,
- We create a list named
list1containing the elements'a', 'b', 'c', 'b', 'a'. - We find the index of the last occurrence of
'b'using the ListlastIndexOf()function, which returns the index of the last occurrence of the specified element. - The last occurrence of
'b'is at index3inlist1, solastIndexBwill be3. - Finally, we print the value of
lastIndexBto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list1 = listOf("a", "b", "c", "b", "a")
val lastIndexB = list1.lastIndexOf("b")
println(lastIndexB)
}Output
3
2 Example
In this example,
- We create a list named
list2containing the integers10, 20, 30, 20, 40. - We find the index of the last occurrence of
20using the ListlastIndexOf()function, which returns the index of the last occurrence of the specified element. - The last occurrence of
20is at index3inlist2, solastIndex20will be3. - Finally, we print the value of
lastIndex20to standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list2 = listOf(10, 20, 30, 20, 40)
val lastIndex20 = list2.lastIndexOf(20)
println(lastIndex20)
}Output
3
3 Example
In this example,
- We create a list named
list3containing the elements'apple', 'banana', 'cherry', 'banana', 'date'. - We try to find the index of the last occurrence of
'grape'using the ListlastIndexOf()function, which returns the index of the last occurrence of the specified element. - Since
'grape'is not present inlist3,lastIndexOf()returns-1. - Finally, we print the value of
lastIndexGrapeto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list3 = listOf("apple", "banana", "cherry", "banana", "date")
val lastIndexGrape = list3.lastIndexOf("grape")
println(lastIndexGrape)
}Output
-1
Summary
In this Kotlin tutorial, we learned about lastIndexOf() function of List: the syntax and few working examples with output and detailed explanation for each example.