Kotlin – Iterate over List of Lists

To iterate over inner lists and elements of these inner lists, in a List of Lists, in Kotlin, we can use nested for loop.

The syntax to iterate over elements of inner lists in a list of lists is

for(aList in listOfLists) {
    for(element in aList) {
        //code
    }
}

Example

In the following example, we will take a List of Lists and iterate over the elements of the inner lists, using for loop.

Main.kt

fun main(args: Array<String>) {
    val listOfLists = listOf(
        listOf(1, 3, 9),
        listOf("Abc", "Xyz", "Pqr")
    )
    for(aList in listOfLists) {
        println("Accessing the list $aList")
        for(element in aList) {
            println(element)
        }
    }
}

Output

Accessing the list [1, 3, 9]
1
3
9
Accessing the list [Abc, Xyz, Pqr]
Abc
Xyz
Pqr

We could iterate over the inner lists, and the elements of these inner lists.

Conclusion

In this Kotlin Tutorial, we learned how to iterate over List of Lists in Kotlin, using for loop.