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]}")
    }


kotlin for loop with 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]}")
        }

kotlin-for-loop-indices-with-string-value.png

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]}")
            }

kotlin-for-loop-arraylist-with-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")
    }

kotlin-for-loop-withIndex

Please add star to AndroidRide repository, if you like.
Please share with your friends and family.

Exit mobile version