Applying Maps in Real-World Scenarios with Kotlin

Introduction and Goal Setting

Hello there! In this lesson, we will apply Maps to real-world challenges. Our focus will be on solving tasks such as cataloging books in a library, counting votes in an election, and tracking inventories.

Real-World Scenarios Calling for Maps

Maps are beneficial in real-life applications, such as the ones mentioned above, due to their ability to rapidly retrieve data with unique keys and efficiently handle larger datasets. Let's understand their efficiency with some actual examples.

Solving Real-World Task 1: Cataloging Books in a Library

Suppose you're asked to manage the cataloging of books in a library. Here, the book ID serves as the key, while the details of the book, such as the title, author, and year of publication, are stored as values.

This approach allows us to add, search for, and remove books from our library catalog using just a few lines of Kotlin code.

Kotlin
fun main() {
    // Initializing a Map
    val libraryCatalog = mutableMapOf<String, MutableMap<String, String>>()

    // Details of a book
    val bookId = "123"
    // Creating a Map to store details of the book
    val bookDetails = mutableMapOf(
        "title" to "To Kill a Mockingbird",
        "author" to "Harper Lee",
        "year_published" to "1960"
    )

    libraryCatalog[bookId] = bookDetails  // Adding a book to library catalog

    // Searching for a book
    if (libraryCatalog.containsKey(bookId)) {
        val details = libraryCatalog[bookId]
        println("Title: ${details?.get("title")}, Author: ${details?.get("author")}, Year Published: ${details?.get("year_published")}")
    }

    libraryCatalog.remove(bookId)  // Removing a book from the library
}

As you can see, Maps make the task of cataloging books in the library simpler and more efficient!

Solving Real-World Task 2: Counting Votes in an Election

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