📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
✅ Some premium posts are free to read — no account needed. Follow me on Medium to stay updated and support my writing.
🎓 Top 10 Udemy Courses (Huge Discount): Explore My Udemy Courses — Learn through real-time, project-based development.
▶️ Subscribe to My YouTube Channel (172K+ subscribers): Java Guides on YouTube
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 ListIterator and a while loop
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
// using forEach() method
fruits.forEach { e -> print("$e ") }
// using for loop
for (fruit in fruits) {
print("$fruit ")
}
for (i in 0 until fruits.size) {
print("${fruits[i]} ")
}
fruits.forEachIndexed({ i, e -> println("fruits[$i] = $e") })
val it: ListIterator<String> = fruits.listIterator()
while (it.hasNext()) {
val e = it.next()
print("$e ")
}
Comments
Post a Comment
Leave Comment