How do i get current index of the list(array) while using foreach loop
Understand how to use Kotlin foreach loop to get the index of the current iteration with RRTutors. Learn this powerful loop structure in Kotlin programming.
While iterate list or array of the data we may require to handle the data with index of the current item. How do we get index while iterate the list/array data with forEach loop.
In kotlin we have different ways to iterate the list/array data
- Using forEachIndexed()
- Using withIndex()
Get current index with forEachIndexed()
forEachIndexed loop is an inline function which will takes inout as an array and reads index and values step by step.
fun main() { var topics = listOf("Kotlin", "Kotlin array", "Kotlin List", "Kotlin Functions") topics.forEachIndexed {index, element -> println("index = $index, item = $element ") } } |
Output:
index = 0, item = Kotlin |
Get current index using withIndex()
fun main() { var topics = listOf("Kotlin", "Kotlin array", "Kotlin List", "Kotlin Functions") for ((index, value) in topics.withIndex()) { println("The topics of $index is $value") } } |
Output:
The topics of 0 is Kotlin |