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
- Using forEach() method
- Using for loop
- An alternative for cycle utilizes the size of the list
- Using forEachIndexed() method
- 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
Post a Comment