Kotlin List – Find Index of an Element

To find the index of a specific element in this List, call indexOf() function on this List, and pass the element as argument to this indexOf() function.

The Kotlin List.indexOf() function finds and returns the index of first occurrence of the element in the list.

Syntax of List.indexOf()

The syntax of List.indexOf() function is

list.indexOf(element)

where

ParameterDescription
elementRequired. The element, whose index to be found in the list.

The datatype of element should match the datatype of elements in list.

Return Value

List.indexOf() function returns the index of the first occurrence of the specified element in the list. If in case, the specified element is not contained in the list, then the function would return -1.

ADVERTISEMENT

Example 1: Find Index of First Occurrence of Element in List

In this example, we will take a list of strings, and find the index of given string in the list.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef")
    val element = "de"
    val index = list1.indexOf(element)
    print("Index of element \"$element\" in the list is $index")
}

Output

Index of element "de" in the list is 3

Example 2: List.indexOf() to Check if Element is in List

If the element is present in the list, then list.indexOf(element), will return a non-negative integer, else it returns -1. We can use this behavior to check if element is present in the list or not.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("ab", "bc", "cd", "de", "ef")
    val element = "de"
    if (list1.indexOf(element) > -1) {
        print("Element is in list.")
    } else {
        print("Element is not in list.")
    }
}

Output

Element is in list.

Conclusion

In this Kotlin Tutorial, we learned how to find the index of a given element in this list, using Kotlin List.indexOf() function.