Kotlin – Get the last index of search element in the Array

Get the last index of search element in the Array in Kotlin

To get the index of last occurrence of given search element in the Array in Kotlin, you can use Array.lastIndexOf() function.

["apple", "banana", "cherry", "banana", "mango"]
  0        1         2         3         4
          "banana"            "banana"
  last occurrence ----------> "banana"
       last index ---------->  3

Call the function lastIndexOf() on the Array object and pass the given search element as argument.

arr.lastIndexOf(searchElement)

The function returns the index of last occurrence of the search element in the Array, if the search element is present. If in case the search element is not present, then the function returns -1.

Examples

Get the last index of “banana” in the Array

In the following program, we take an Array of strings in arr and a search element in searchElement. We find the last index of the search element in the array using Array.lastIndexOf() function.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "banana", "mango")
    val searchElement = "banana"
    val index = arr.lastIndexOf(searchElement)
    println("last index : $index")
}

Output

last index : 3

Explanation

["apple", "banana", "cherry", "banana", "mango"]
  0        1         2         3         4
          "banana"            "banana"
  last occurrence ----------> "banana"
       last index ---------->  3

What is the last index of search element if the search element is not present in the Array

In the following program, we take an Array of strings in arr and a search element in searchElement. The value in searchElement is such that it is not present in the given Array arr.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "banana", "mango")
    val searchElement = "fig"
    val index = arr.lastIndexOf(searchElement)
    println("last index : $index")
}

Output

last index : -1

Since the search element is not present in the Array, lastIndexOf() function returned -1.