Site icon AndroidRide

Kotlin For loop with Index example

Hi, Welcome to AndroidRide!.

Let’s learn about Kotlin for loop with index.

For loop with indices property

In this simple example, we will use indices property of collections to get the index.

    val items = listOf("A","B", "C")

    for(index in items.indices){
        println("indices: $index, item: ${items[index]}")
    }


For loop with string value

In this section, we can use indices property with string value.

 val strValue = "String"
        for(i in strValue.indices){
            println("index: $i, char: ${strValue[i]}")
        }

ArrayList with index example

Kotlin arraylist helps to store data in dynamic array.

    val arrayListItems = arrayListOf("Item 1", "Item 2", "Item 3")
        for(index in arrayListItems.indices){
            println("ArrayList with index: ${arrayListItems[index]}")
            }

Using withIndex() method

If you need both the index and the item while iterating, use withIndex().

 val char = arrayOf("a", "b", "c")
    for ((index, ch) in char.withIndex()) {
        println("Index: $index, character: $ch")
    }

package com.androidride.kotlin

fun main() {

    val items = listOf("A", "B", "C")
    for (index in items.indices) {
        println("indices: $index, item: ${items[index]}")
    }

    val strValue = "String"
    for (i in strValue.indices) {
        println("index: $i, char: ${strValue[i]}")
    }

    val arrayListItems = arrayListOf("Item 1", "Item 2", "Item 3")
    for (index in arrayListItems.indices) {
        println("ArrayList with index: ${arrayListItems[index]}")
    }

    for ((index, item) in items.withIndex()) {
        println("withIndex: index: $index, item: $item")
    }

}


  • Android WebView Tutorial
  • Kotlin control flow docs
  • Please add star to AndroidRide repository, if you like.
    Please share with your friends and family.

    Exit mobile version