How do i get current index of the list(array) while using foreach loop
Published October 07, 2022While 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 |
Article Contributed By :
|
|
|
|
206 Views |