How do i get current index of the list(array) while using foreach loop

Published October 07, 2022

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 
index = 1, item = Kotlin array 
index = 2, item = Kotlin List 
index = 3, item = Kotlin Functions 

 

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
The topics of 1 is Kotlin array
The topics of 2 is Kotlin List
The topics of 3 is Kotlin Functions

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

76 Views