This article explores different ways to traverse a list with the index in Kotlin.

1. Using ListIterator

A simple solution is to use the nextIndex() function from the iterator returned by the ListIterator. It returns the index of an element which will be returned by a subsequent call to the next() function. It should be invoked before calling the next() function. Alternatively, we can invoke the previousIndex() function after calling the next() function.

 
The following code example shows invocation for this method:

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

2. Using Loop

Another option is to maintain a primitive counter, starting with 0, and increment the counter by 1 with each iteration of the loop. This can be implemented as follows in Kotlin.

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

 
Alternatively, we can iterate over the range of indices, and use it to get the index and the corresponding element.

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

 
Here’s an equivalent version using the forEach() method:

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

3. Using forEachIndexed() function

Another viable alternative is to leverage the forEachIndexed() function, which provides a sequential index with the element and performs an action on each element. This would translate to a simple code below:

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

4. Using withIndex() function

An alternative idea is to use the withIndex() function that wraps each element of a list into an IndexedValue containing the index of that element and the element itself. This is demonstrated below:

Download Code

Output:

Index: 0, Item: 4
Index: 1, Item: 2
Index: 2, Item: 5
Index: 3, Item: 4
Index: 4, Item: 1

That’s all about traversing a list with the index in Kotlin.