What is the ArrayList.lastIndexOf() method in Kotlin?

The kotlin.collections package is part of Kotlin’s standard library, and it contains all collection types, such as Map, List, Set, etc. The package provides the ArrayList class, a mutable list, and uses a dynamically resizable array as the backing storage.

The ArrayList class contains the lastIndexOf() method, which returns the index of the last occurrence of the specified element in the list and -1 if the element is not present in the list.

Syntax

fun lastIndexOf(element: E): Int

Arguments

  • This method takes the element to search as input.

Return value

  • It returns the last index of the element in the list and -1 if the input element is not present.

Things to note

  • ArrayList follows the sequence of insertion of elements.

  • It is allowed to contain duplicate elements.

The illustration below shows the function of the lastIndexOf() method.

Getting last index of a element in the array list using the lastIndexOf() method
fun main(args : Array<String>) {
val sportsList = ArrayList<String>()
sportsList.add("Cricket")
sportsList.add("Football")
sportsList.add("Tennis")
sportsList.add("Football")
sportsList.add("Racing")
println("Printing ArrayList elements --")
println(sportsList)
var lastIndex = sportsList.lastIndexOf("Football")
println("Last Index of 'Football' is ${lastIndex}")
lastIndex = sportsList.lastIndexOf("Hockey")
println("Last Index of 'Hockey' is ${lastIndex}")
}

Explanation

  • Line 2: We create an empty array list named sportsList to store the strings.

  • Line 4 to 7: We add a few sport names to the ArrayList object using the add() method, such as: "Cricket", "Football", "Tennis", "Football", and "Racing".

  • Line 11: We call the lastIndexOf() method and pass the input string as "Football". It returns 3 as "Football" exists twice, first at index 1 and last at index 3 in the list.

  • Line 13: We call the lastIndexOf() method and pass the input string as "Hockey". It returns -1, as "Hockey" does not exist in the list.

The ArrayList elements and result of the lastIndexOf() method are displayed using the println() function of the kotlin.io package.

Free Resources