To iterate over a list in Kotlin, you can use various methods such as for
loop, forEach
method, forEachIndexed
method, etc.
In this example,
listOfNumbers
containing integer values.for
loop to iterate over each element in the listOfNumbers
.fun main() {
val listOfNumbers = listOf(1, 2, 3, 4, 5)
for (number in listOfNumbers) {
println(number)
}
}
1 2 3 4 5
In this example,
listOfColors
containing string values.forEach
method on listOfColors
to iterate over each element in the list.forEach
lambda, we print each element to standard output.fun main() {
val listOfColors = listOf("Red", "Green", "Blue", "Yellow", "Orange")
listOfColors.forEach { color ->
println(color)
}
}
Red Green Blue Yellow Orange
In this example,
listOfNames
containing string values.forEachIndexed
method on listOfNames
to iterate over each element in the list along with its index.forEachIndexed
lambda, we print the index and each element to standard output.fun main() {
val listOfNames = listOf("Alice", "Bob", "Charlie", "David", "Emily")
listOfNames.forEachIndexed { index, name ->
println("Index: $index, Name: $name")
}
}
Index: 0, Name: Alice Index: 1, Name: Bob Index: 2, Name: Charlie Index: 3, Name: David Index: 4, Name: Emily
In this tutorial, we learned How to Iterate Over a List in Kotlin language with well detailed examples.