Find index of an element in a Kotlin List
This article explores different ways to find the index of an element in a Kotlin List.
1. Using indexOf() function
The recommended solution to get the index of an element in a list is with the indexOf() library function. It returns the index of the first occurrence of the provided element in the list, or -1 if the element is not present.
|
1 2 3 4 5 6 7 |
fun main() { val values = listOf(4, 7, 2, 5, 1, 9, 5, 3) val item = 5 val index = values.indexOf(item) println(index) // 3 } |
2. Using withIndex() function
The idea here is to get an iterable containing the index of each element of the list and the element itself using the withIndex() function. Then return the index of the first pair that match the given value. This would translate to the following code:
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val values = listOf(4, 7, 2, 5, 1, 9, 5, 3) val item = 5 val index = values.withIndex() .first { item == it.value } .index println(index) // 3 } |
3. Using find() function
Another viable alternative is to filter the indices containing the given element using the find() function, which returns the first element matching the given predicate, or null if no such element exists. This would translate to a simple code below:
|
1 2 3 4 5 6 7 |
fun main() { val values = listOf(4, 7, 2, 5, 1, 9, 5, 3) val item = 5 val index = values.indices.find { values[it] == item } println(index) // 3 } |
4. Using Loop
Following is an equivalent version using the for loop, which returns the index of the first occurrence, or -1 if no matching element is found.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun findIndex(values: List<Int>, item: Int): Int { for (i in values.indices) { if (values[i] == item) { return i } } return -1 } fun main() { val values = listOf(4, 7, 2, 5, 1, 9, 5, 3) val item = 5 val index = findIndex(values, item) println(index) // 3 } |
That’s all about finding the index of an element in a Kotlin List.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)