5 Ways to Iterate Over a List in Kotlin

In this quick article, I show you five ways of looping over a list in Kotlin.
List iteration or list looping is the process of going through the list elements one by one.

5 Ways to Iterate Over a List in Kotlin

  1. Using forEach() method
  2. Using for loop
  3. An alternative for cycle utilizes the size of the list
  4. Using forEachIndexed() method
  5. Using a ListIterator and a while loop
Here is a complete source code to demonstrate five ways of looping over a list in Kotlin.
package net.sourcecodeexamples.kotlin


fun main() {

     val fruits = listOf("banana", "mango", "apple", "orange")

      // using forEach() method
     fruits.forEach { e -> print("$e ") }
     println()

     // using for loop
     for (fruit in fruits) {
          print("$fruit ")
     }

     println()

     // An alternative for cycle utilizes the size of the list
     for (i in 0 until fruits.size) {
          print("${fruits[i]} ")
     }

     println()

     // using forEachIndexed() method
     fruits.forEachIndexed({ i, e -> println("fruits[$i] = $e") })

     // using a ListIterator and a while loop
     val it: ListIterator<String> = fruits.listIterator()

     while (it.hasNext()) {
           val e = it.next()
           print("$e ")
     }

     println()
}

Output

banana mango apple orange 
banana mango apple orange 
banana mango apple orange 
fruits[0] = banana
fruits[1] = mango
fruits[2] = apple
fruits[3] = orange
banana mango apple orange 

Explanation

The forEach() performs the given action on each list element. We pass it an anonymous function that prints the current element -
// using forEach() method
fruits.forEach { e -> print("$e ") }
We loop the list with for. The for loop traverses the list element by element; in each cycle, the word variable points to the next element in the list -
        // using for loop
 for (fruit in fruits) {
      print("$fruit ")
 }
An alternative for cycle utilizes the size of the list. The until keyword creates a range of the list indexes -
        for (i in 0 until fruits.size) {
            print("${fruits[i]} ")
        }
With the forEachIndexed() method, we loop over the list having index and value available in each iteration.
fruits.forEachIndexed({ i, e -> println("fruits[$i] = $e") })
The final way is using a ListIterator and a while loop -
       val it: ListIterator<String> = fruits.listIterator()

       while (it.hasNext()) {
            val e = it.next()
            print("$e ")
       }

Comments