To iterate over a Two-Dimensional List in Kotlin, you can use nested loops, with an outer loop iterating over rows and an inner loop iterating over columns. The outer loop iterates over each row of the 2D list, while the inner loop iterates over each element in the current row.
In this example,
fun main() {
val matrix = listOf(
listOf(1, 2, 3),
listOf(4, 5, 6),
listOf(7, 8, 9)
)
for (row in matrix) {
for (element in row) {
print("$element ")
}
println()
}
}
1 2 3 4 5 6 7 8 9
In this example,
fun main() {
val matrix = listOf(
listOf("apple", "banana"),
listOf("cherry", "orange")
)
for (row in matrix) {
for (element in row) {
print("$element ")
}
println()
}
}
apple banana cherry orange
In this tutorial, we learned How to Iterate over a Two Dimensional List in Kotlin language with well detailed examples.