Kotlin List lastIndexOf()
Syntax & Examples


Syntax of List.lastIndexOf()

The syntax of List.lastIndexOf() function is:

abstract fun lastIndexOf(element: E): Int

This 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 list1 containing the elements 'a', 'b', 'c', 'b', 'a'.
  • We find the index of the last occurrence of 'b' using the List lastIndexOf() function, which returns the index of the last occurrence of the specified element.
  • The last occurrence of 'b' is at index 3 in list1, so lastIndexB will be 3.
  • Finally, we print the value of lastIndexB to standard output using the println function.

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 list2 containing the integers 10, 20, 30, 20, 40.
  • We find the index of the last occurrence of 20 using the List lastIndexOf() function, which returns the index of the last occurrence of the specified element.
  • The last occurrence of 20 is at index 3 in list2, so lastIndex20 will be 3.
  • Finally, we print the value of lastIndex20 to standard output using the println function.

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 list3 containing the elements 'apple', 'banana', 'cherry', 'banana', 'date'.
  • We try to find the index of the last occurrence of 'grape' using the List lastIndexOf() function, which returns the index of the last occurrence of the specified element.
  • Since 'grape' is not present in list3, lastIndexOf() returns -1.
  • Finally, we print the value of lastIndexGrape to standard output using the println function.

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.