How to Iterate Over List in Kotlin: Simple Examples
In Kotlin, you can iterate over a list using a
for loop or the forEach function. Use for (item in list) to access each element, or list.forEach { item -> } for a lambda-based approach.Syntax
To loop through a list in Kotlin, use the for loop or the forEach function.
- for loop:
for (item in list) { /* code */ }runs code for each item. - forEach function:
list.forEach { item -> /* code */ }uses a lambda to process each item.
kotlin
val list = listOf("apple", "banana", "cherry") // Using for loop for (item in list) { println(item) } // Using forEach function list.forEach { item -> println(item) }
Example
This example shows how to print each fruit in a list using both for loop and forEach function.
kotlin
fun main() {
val fruits = listOf("apple", "banana", "cherry")
println("Using for loop:")
for (fruit in fruits) {
println(fruit)
}
println("Using forEach function:")
fruits.forEach { fruit ->
println(fruit)
}
}Output
Using for loop:
apple
banana
cherry
Using forEach function:
apple
banana
cherry
Common Pitfalls
Common mistakes when iterating over lists in Kotlin include:
- Using an index-based loop incorrectly, which can cause errors if the index is out of bounds.
- Modifying the list while iterating, which can cause runtime exceptions.
- Forgetting to use
inkeyword in theforloop.
Always prefer for (item in list) or forEach for safe and clear iteration.
kotlin
val list = listOf("a", "b", "c") // Wrong: missing 'in' keyword // for (item list) { // println(item) // } // Correct: for (item in list) { println(item) }
Quick Reference
| Method | Syntax | Description |
|---|---|---|
| For loop | for (item in list) { /* code */ } | Simple and readable loop over each element. |
| forEach function | list.forEach { item -> /* code */ } | Lambda-based iteration, useful for inline actions. |
| Indexed loop | for (index in list.indices) { val item = list[index] } | Access elements with index, use carefully. |
| While loop | var i = 0; while (i < list.size) { val item = list[i]; i++ } | Less common, manual index control. |
Key Takeaways
Use 'for (item in list)' for simple and clear iteration over lists.
The 'forEach' function offers a concise lambda-based way to loop through lists.
Avoid modifying a list while iterating to prevent errors.
Remember to include the 'in' keyword in 'for' loops to avoid syntax errors.
Use indexed loops only when you need the position of elements.