To find the index of a specified element in a list in Kotlin, you can use the indexOf
method of the List class.
In this example,
myList
with some elements.indexOf
method of the list object myList
to find the index of a specific element.indexOf
method returns the index of the first occurrence of the element in the list, or -1 if the element is not found.fun main() {
val myList = listOf(10, 20, 30, 40, 50)
val index = myList.indexOf(40)
println("Index of element is: $index")
}
Index of element is: 3
In this example,
myList
with some string elements.indexOf
method of the list object myList
to find the index of a specific string.indexOf
method returns the index of the first occurrence of the string in the list, or -1 if the string is not found.fun main() {
val myList = listOf("apple", "banana", "cherry", "date", "elderberry")
val index = myList.indexOf("cherry")
println("Index of element is: $index")
}
Index of element is: 2
In this tutorial, we learned How to get the Index of Specified Element in a List in Kotlin language with well detailed examples.