Kotlin Set Iterate Example - forEach(), for Loop, forEachIndexed() and Iterator

In this quick article, I show you five ways of looping over a Set in Kotlin.

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 Iterator and a while loop
Here is a complete source code to demonstrate five ways of looping over a Set inKotlin.
package net.sourcecodeexamples.kotlin


fun main() {

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

    // 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.elementAt(i)} ")
    }

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


    val it: Iterator < String > = fruits.asIterable().iterator();

    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 


Comments