📘 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.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare 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