Lesson 47 – Map and MutableMap in Kotlin Programming language

Lesson 47 – Map and MutableMap in Kotlin Programming language

Hello viewer, You can now have our Tutorial Lessons in your android mobile device and read it offline.
Download kotlin Programming APP on PlayStore
Download Website SEO Lessons APP on PlayStore

The Map data structure uses a key to access a value. The subindex can be any type of class, as well as its value

We can relate it to concepts we know:

  • A traditional dictionary that we know can use a Map of Kotlin to represent it. The key would be the word and the value would be the definition of that word.
  • A personal agenda can also be represented as a Map. The date would be the key and the activities of that date would be the value.
  • A set of users of a website we can store it in a Map. The username would be the key and as a value we could store your mail, password, login dates etc.

There are many problems of reality that can be represented by a Map.

Problem 1

In the main block of the program define an immutable Map that stores the names of countries as a key and value the number of inhabitants of that country.
Test different methods and properties provided by the Map class.

Project 181

fun main (args: Array <String>) {
    val countries: Map <String, Int> = mapOf (Pair ("argentina", 40000000),
            Pair ("Spain", 46000000),
            Pair ("uruguay", 3400000))
    println ("Complete Map Listing")
    println (countries)
// www.coding180.com
    for ((key, value) in countries)
        println ("For the key $key we have stored $value")
    println ("The number of map elements is ${countries.size}")
    val CanInhabitants1: Int? = countries ["argentina"]
    
    if (CanInhabitants1 != null)
    println ("The number of inhabitants of Argentina is $CanInhabitants1")
    
    val CanInhabitants2: Int? = countries ["Brazil"]
    if (CanInhabitants2 != null)
    println ("The number of inhabitants of Brazil is $CanInhabitants2")
    else
    println ("Brazil is not loaded in the Map")
    var sum = 0
    countries.forEach {sum += it.value}
    println ("Total number of inhabitants of all countries is $sum")
}

To create a Map in Kotlin Programming Language we must define a variable and indicate what kind of data is the key of the map and the value that it stores.
Using the mapOf  function we return a Map indicating each entry in our Map using a Pair object:

    Val countries: Map <String, Int >= mapOf (Pair ("argentina", 40000000),
                                          Pair ("Spain", 46000000),
                                          Pair ("uruguay", 3400000))

We have created a Map that stores three entries.

The println function allows us to display the Map completely:

    Println ("Complete Map Listing")
    Println (countries)

If we want to go through and print element by element the components of the map we can do it by a FOR, in each iteration we retrieve a key and its value:

    For ((key, value) in countries)
        Println ("For the key $key we have stored $value")

Like the lists, the Map class has a size property that returns the number of map elements:

    Println ("The number of map elements is ${country.size}")

If we need to recover the value for a certain key we can do it through the syntax:

    Val CanInhabitants1: Int? = Countries ["argentina"]

As it can happen that the key searched in the map does not exist, we define the variable CanInhabitants1 of Int? Since it can store a null if the country does not exist.

Then with an if we can control if the number of inhabitants for the searched country was recovered:

    If (CanInhabitants1! = Null)
        Println ("The number of inhabitants of Argentina is $cantHabitantes1")
    Val CanInhabitants2: Int? = Countries ["Brazil"]
    If (CanInhabitants2! = Null)
        Println ("The number of inhabitants of Brazil is $CanInhabitants2")
    Else
        Println ("Brazil is not loaded in the Map")

Finally,  to accumulate a number of inhabitants of all the countries, we can cross the Map and add the value of each component:

    Var sum = 0
    Paises.forEach {sum + = it.value}
    Println ("Total number of inhabitants of all countries is $ sum")

Another common syntax for creating the Map in Kotlin is:

    Val countries: Map <String, Int> = mapOf ("argentina" to 40000000,
                                          "Spain" to 46000000,
                                          "Uruguay" to 3400000)

The function “to” we will see that through an “infix” definition we can pass a parameter, then the function name and finally the second parameter. The to function already exists and has this syntax:

Public infix fun <A, B> A. (that: B): Pair <A, B> = Pair (this, that)

We will see later functions with infix notation and with generic parameters. We can verify that the function returns an object of class Pair.

If we want to know all the properties and methods of Map we can visit the documentation of the standard library of Kotlin.

Problem 2

Create a map that allows you to store 5 articles, use the product name as a key and value the price.
Further, develop the functions of:
1) Print the dictionary completely
2) Show the number of articles with a price higher than 20.

Project 182

fun print (products: Map <String, Float>) {
    for ((key, value) in products)
        println ("$key has a price $value")
    println();
}
// www.coding180.com
fun quantityPrice20 (products: Map <String, Float>) {
    val cont = products.count {it.value> 20}
    println ("Number of products with a price greater than 20: $cont")
}

fun main (args: Array <String>) {
    val products: Map <String, Float> = mapOf ("pops" to 12.5f,
            "Apples" to 26f,
            "Pears" to 31f,
            "Mandarins" to 15f,
            "Pomelos" to 28f)
    print (products)
    quantityPrice20(products)
}

In this case, we create a map whose key is of type String and its value is a Float:

Fun main (args: Array <String>) {
    Val products: Map <String, Float> = mapOf ("pops" to 12.5f,
                                              "Apples" to 26f,
                                              "Pears" to 31f,
                                              "Mandarins" to 15f,
                                              "Pomelos" to 28f)

To show the map in a complete form, we do it by means of a FOR:

fun print (products: Map <String, Float>) {
    For ((key, value) in products)
        Println ("$key has a price $value")
    Println ();
}

To count the number of products that have a price greater than 20, we call the count method and pass it a lambda function by analyzing its parameter in the value property if it satisfies the condition of exceeding the value 20:

Fun quantityPrice20(products: Map <String, Float>) {
    Val cont = products.count {it.value> 20}
    Println ("Number of products with a price greater than 20: $cont")
}

Problem 3

Develop an application that allows us to create an English / Spanish dictionary. The key is the word in English and the value is the word in Spanish.
Create the following functions:
1) Load the dictionary (enter the word in English and translate it in Spanish)
2) Complete dictionary listing.
3) Enter a word in English and if there is in the dictionary display its translation.

Project 183

fun load (dictionary: MutableMap <String, String>) {
    do {
        print ("Enter word in Spanish:")
        val tSpanish = readLine () !!
        print ("Enter word in English:")
        val tEnglish = readLine () !!
        dictionary [tEnglish] = tSpanish
        print ("Continue loading another word in the dictionary? (Yes / no):")
        val fin = readLine () !!
    } while (fin == "yes")
}
// www.coding180.com
fun list (dictionary: MutableMap <String, String>) {
    for ((English, Spanish) in dictionary)
        println ("$English: $Spanish")
    println ()
}

fun querylng (dictionary: MutableMap <String, String>) {
    print ("Enter a word in English to verify your translation:")
    val English = readLine ()
    if (English in dictionary)
        println ("The translation into English is ${dictionary [English]}")
    else
        println ("There is no such word in the dictionary")
}

fun main (args: Array <String>) {
    val dictionary: MutableMap <String, String> = mutableMapOf ()
    load (dictionary)
    list (dictionary)
    querylng (dictionary)
}

In the main function we define an empty MutableMap:

Fun main (args: Array <String>) {
    Val dictionary: MutableMap <String, String> = mutableMapOf ()

In the function load we proceed to enter a word in English and its translation in Spanish, to load it to Map we proceed to access through the subscript:

        Print ("Enter word in Spanish:")
        Val tSpanish= readLine () !!
        Print ("Enter word in English:")
        Val tEnglish= readLine () !!
        Dictionary [tEnglish] = tSpanish

The load function ends when the operator loads a String other than “yes”:

        Print ("Continue loading another word in the dictionary? (Yes / no):")
        Val fin = readLine () !!
    } While (fin == "yes")

To control if a Map contains a certain key we can do it with the operator in:

    Print ("Enter a word in English to verify your translation:")
    Val English = readLine ()
    If (English in dictionary)
        Println ("The translation into English is ${dictionary [English]}")
    Else
        Println ("There is no such word in the dictionary")

If we want to know all the properties and methods of MutableMap we can visit the documentation of the standard library of Kotlin.

Problem 4

Make a program that allows loading a product code as a key in a Map. Save for that key an object of the Product class that defines as properties its name of the product, its price and quantity in stock.

Implement the following activities:
1) Load data into the Map.
2) A complete list of products.
3) Query a product by its key, show the name, price and stock.
4) The quantity of products that have a stock with zero value.

Project 184

data class Product (val name: String, val price: Float, val quantity: Int)

fun load (products: MutableMap <Int, Product>) {
    products [1] = Product ("Popes", 13.15f, 200)
    products [15] = Product ("Apples", 20f, 0)
    products [20] = Product ("Pears", 3.50f, 0)
}

fun listComplete (products: MutableMap <Int, Product>) {
    println ("Complete product list")
    for ((code, product) in products)
        println ("Code: $code Description ${product.name} Price: ${product.price} Current Stock: ${product.price}")
    println()
}
// coding180.com
fun product (products: MutableMap <Int, Product>) {
    print ("Enter the code for a product:")
    val code = readLine () !!. toInt ()
    if (code in products)
        println ("Name: ${products [code]?.name} Price: ${products [code]?.price} Stock: ${products [code]?.quantity}")
        else
        println ("There is no product with this code")
        }

        fun sinStock (products: MutableMap <Int, Product>) {
            val cont = products.count {it.value.quantity == 0}
            println ("Number of items not in stock: $cont")
        }

        fun main (args: Array <String>) {
            val products: MutableMap <Int, Product> = mutableMapOf ()
            load (products);
            listComplete (products)
             product (products)
            sinStock (products)
        }

We define a Map mutable in the main function and call a series of functions where in one we load it and in the rest we process its elements:

Fun main (args: Array <String>) {
    Val products: MutableMap <Int, Product> = mutableMapOf ()
    Load (products);
    ListingComplete (products)
    product (products)
    SinStock (products)
}

In the load function comes the Map and we add three products:

Fun load (products: MutableMap <Int, Product>) {
    Products [1] = Product ("Popes", 13.15f, 200)
    Products [15] = Product ("Apples", 20f, 0)
    Products [20] = Product ("Pears", 3.50f, 0)
}

The function that analyzes the quantity of products without stock we do it by calling count and passing a lambda function that will count all the products whose quantity is zero:

Fun sinStock (products: MutableMap <Int, Product>) {
    Val cont = products.count {it.value.quantity == 0}
    Println ("Number of items not in stock: $cont")
}

Problem 5

You want to store the data of n students (n is entered by keyboard). Define a MutableMap whose key is the student’s document number.
As a value store a list with components of the class Material where we store the name of matetrial and its note.

Create the following functions:
1) Studentload (of each student request his / her days and the names of the subjects and their notes)
2) List of all the students with their notes
3) Consultation of a student by his days, Materials and notes.

Project 185

data class Material (val name: String, val note: Int)

fun Studentload (students: MutableMap <Int, MutableList <Material>>) {
    print ("How many students will be charged?")
    val cant = readLine () !!. toInt ()
    for (i in 1..cant) {
        print ("Enter dni:")
        val days = readLine () !!. toInt ()
        val listMaterials = mutableListOf <Material> ()
// www.coding180.com
        do {
            print ("Enter student subject:")
            val name = readLine () !!
            print ("Enter note:")
            val note = readLine () !!. toInt ()
            listMaterials.add(Material (name, note))
            print ("Enter another note (yes / no):")
            val option = readLine () !!
        } while (option == "yes")
        students [days] = listMaterials
    }
}

fun print (students: MutableMap <Int, MutableList <Material>>) {
    for ((days, listMaterials) in students) {
        println ("Student Days: $days")
        for (material in listMaterials) {
            println ("Subject: ${material.name}")
            println ("Note: ${material.note}")
        }
        println ()
    }
}

fun InquirebyDays (students: MutableMap <Int, MutableList <Material >>) {
    print ("Enter the student ID to consult:")
    val dni = readLine () !!. toInt ()
    if (dni in students) {
        println ("Study the following subjects")
        val list = students [dni]
        if (list != null)
        for ((name, note) in list) {
            println ("Subject name: $name")
            println ("Note: $note")
        }
    }
}

fun main (args: Array <String>) {
    val students: MutableMap <Int, MutableList <Material>> = mutableMapOf ()
    Studentload(students)
    print (students)
    InquirebyDays (students)
}

As we have to represent more complex concepts we need to define in this case a Map whose key is an integer but its value is a mutable list with elements of the class Subject:

Fun main (args: Array <String>) {
    Val students: MutableMap <Int, MutableList <Subject >> = mutableMapOf ()

In the function of loading before a for we request the number of students to store on the map:

Fun load (students: MutableMap <Int, MutableList <Matter >>) {
    Print ("How many students will be charged?")
    Val cant = readLine () !!. ToInt ()

Then by means of a for we proceed to load the days of the student and create a mutable list where the materials and their respective notes of the student will be stored:

    For (i in 1..cant) {
        Print ("Enter days:")
        Val days = readLine () !!. ToInt ()
        Val listMaterials = mutableListOf <Subject> ()

Through a repetitive structure we load each subject and note until we finish with that student:

        Do {
            Print ("Enter student subject:")
            Val name = readLine () !!
            Print ("Enter note:")
            Val note = readLine () !!. ToInt ()
            List.add (Subject (name, note))
            Print ("Enter another note (yes / no):")
            Val option = readLine () !!
        } While (option == "yes")

When we leave the cycle do / while we proceed to insert the list of subjects on the map:

        Students [days] = listMaterials
    }
}

To print the map completely, we will walk with a for that rescues in each cycle the student’s ID and the list of subjects that he/she studies:

Fun print (students: MutableMap <Int, MutableList <Matter >>) {
    For ((dni, listMaterials) in students) {
        Println ("Student Days: $days")

Through another, for internal, we cross the list of subjects of that student and we show the names of subjects and their notes:

        For (materia in listMaterials) {
            Println ("Subject: ${subject.name}")
            Println ("Note: ${subject.note}")
        }
        Println ()
    }
}

Finally, the consultation of the subjects that a student is entering is entered the days and after controlling if it is stored on the map we proceed with a cycle for all the subjects that it courses:

Fun InquirebyDays(students: MutableMap <Int, MutableList <Subject >>) {
    Print ("Enter the student ID to consult:")
    Val days = readLine () !!. ToInt ()
    If (days in students) {
        Println ("Study the following subjects")
        Val list = students [days]
        If (list! = Null)
            For ((name, note) in list) {
                Println ("Subject name: $name")
                Println ("Note: $note")
            }
    }
}

Proposed problem

  • Make an agenda. Use a MutableMap whose key is of the class Date:
    Data class Date (val day: Int, val month: Int, val year: Int)
    

    As a value in the map store a String.
    Implement the following functions:
    1) Loading data into the agenda.
    2) Complete list of the agenda.
    3) Consultation of a date.

Solution

About The Author

Related posts

Leave a Reply