Introduction

Welcome to our exploration of Compound Data Structures in Kotlin. Having navigated through Maps, Sets, and Lists, we'll delve into nested maps and lists. These structures enable us to handle complex and hierarchical data, which is typical in real-world scenarios. This lesson will guide you through a recap of the basics, the creation and modification of nested maps and lists, as well as common error handling.

Recap: Maps, Lists, and Understanding Nested Structures

Here's a simple example of a school directory that uses a map with grades as keys and lists of students as values:

fun main() {
    // Map with grades as keys and lists of students as values
    val schoolDirectory = mapOf(
        "Grade1" to listOf("Amy", "Bobby", "Charlie"),
        "Grade2" to listOf("David", "Eve", "Frank"),
        "Grade3" to listOf("George", "Hannah", "Ivy")
    )

    // Prints the Grade1 list in the map
    println(schoolDirectory["Grade1"]) // Output: [Amy, Bobby, Charlie]
}
Creating Nested Maps and Lists

Just like their non-nested versions, creating nested structures is straightforward. Kotlin's data classes can be leveraged for better organization when needed.

Nested Map:

fun main() {
    // Map within a map
    val nestedMap = mapOf(
        "fruit" to mapOf(
            "apple" to "red",
            "banana" to "yellow"
        ),
        "vegetable" to mapOf(
            "carrot" to "orange",
            "spinach" to "green"
        )
    )

    // Prints the nested map
    println(nestedMap)
    // Output: {fruit={apple=red, banana=yellow}, vegetable={carrot=orange, spinach=green}}
}

Nested List:

fun main() {
    // Lists within a list
    val nestedList = listOf(
        listOf(1, 2, 3),  // inner list within the outer list
        listOf(4, 5, 6),  // another inner list within the outer list
        listOf(7, 8, 9)   // third inner list within the outer list
    )

    // Prints the nested list
    println(nestedList) // Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
}

Lists within a Map:

fun main() {
    // Lists within a map
    val listMap = mapOf(
        "numbers" to listOf(1, 2, 3),
        "letters" to listOf("a", "b", "c")
    )

    // Prints the map of lists
    println(listMap) // Output: {numbers=[1, 2, 3], letters=[a, b, c]}
}
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal