Kotlin List.lastIndexOf() – Examples

Kotlin List.lastIndexOf()

The Kotlin List.lastIndexOf() function returns the index of the last occurrence of the specified element in the list.

Syntax

List.lastIndexOf(element)

Note: The function returns -1 if the element is not present in the list.

Example 1

In this example,

  1. Take a list of integers.
  2. Take an element whose index of last occurrence has to be found out in this list.
  3. Call lastIndexOf() function on this list and pass the specific element to the function as argument.

Program

fun main(args: Array<String>) {
    val list1 = listOf(4, 7, 9, 7, 1, 3)
    val element = 7
    val lastIndex = list1.lastIndexOf( element )
    print(lastIndex)
}

The element 7 has occurred in the indices 1 and 3. Since, lastIndexOf() returns the index of last occurrence, the function’s return value is 3.

Output

3

Example 2

In this example,

  1. Take a list of strings.
  2. Take an element whose index of last occurrence has to be found out in this list.
  3. Call lastIndexOf() function on this list and pass the specific element to the function as argument.

Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "google", "apple", "bing")
    val element = "apple"
    val lastIndex = list1.lastIndexOf( element )
    print(lastIndex)
}

Output

2

Example 3

In this example,

  1. Take a list of strings.
  2. Take an element which is not present in this list.
  3. Call lastIndexOf() function on this list and pass the specific element to the function as argument.
  4. As the element is not present, the function should return -1.

Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "google", "apple", "bing")
    val element = "sony"
    val lastIndex = list1.lastIndexOf( element )
    print(lastIndex)
}

Output

-1