Maps are an essential part of Kotlin. The map allows us to store data in a structured way. A map data is stored in Key-Value pair format, and each key should be unique and connected to a specific value. In today’s tutorial, we will explore Map in depth. Map’s main purpose is to retrieve values based on their Key.
Basic types of Maps:
- Immutable Map: Immutable maps cannot be modified after declaration. Once you define an immutable map you cannot perform a CURD operation on it.
1val fruits = mapOf("apple" to 1, "banana" to 2, "orange" to 3) - Mutable Map: Mutable maps can be modified.
1val mutableFruits = mutableMapOf("apple" to 1, "banana" to 2)
Adding duplicate items in Map:
If we intentionally add duplicate items to the Map, it will not add the same item with the same key. But we can assign the same value to a unique key. See the mentioned example for more clarity.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun main() { val mutableFruits = mutableMapOf("apple" to 1, "banana" to 2, "apple" to 1, "mango" to 1) // "apple" is the KEY and "1" is its value. // "banana" is the KEY and "2" is its value. // "mango" is the KEY and "1" is its value. println(mutableFruits) } // Output {apple=1, banana=2, mango=1} |
Understanding Maps in Kotlin: A Comprehensive Guide to Key-Value Pairs
- String Key Int Value Map.
123456789101112131415val stringToIntMap = mutableMapOf("apple" to 1, "banana" to 2, "cherry" to 3)// Add a new entrystringToIntMap["date"] = 4// Update an existing entrystringToIntMap["apple"] = 10// Remove an entrystringToIntMap.remove("banana")// Print the mapprintln(stringToIntMap)// Output: {apple=10, cherry=3, date=4} - Int Key String Value Map.
12345678910111213141516val intToStringMap = mutableMapOf(1 to "one", 2 to "two", 3 to "three")// Add a new entryintToStringMap[4] = "four"// Update an existing entryintToStringMap[2] = "TWO"// Remove an entryintToStringMap.remove(3)// Print the mapprintln(intToStringMap)// Output: {1=one, 2=TWO, 4=four} - String Key Boolean Value Map.
12345678910111213141516val stringToBooleanMap = mutableMapOf("isActive" to true, "isVerified" to false)// Add a new entrystringToBooleanMap["isSubscribed"] = true// Update an existing entrystringToBooleanMap["isActive"] = false// Remove an entrystringToBooleanMap.remove("isVerified")// Print the mapprintln(stringToBooleanMap)// Output: {isActive=false, isSubscribed=true} - Double Key String Value Map.
12345678910111213141516val doubleToStringMap = mutableMapOf(1.1 to "Low", 2.5 to "Medium")// Add a new entrydoubleToStringMap[3.9] = "High"// Update an existing entrydoubleToStringMap[1.1] = "Very Low"// Remove an entrydoubleToStringMap.remove(2.5)// Print the mapprintln(doubleToStringMap)// Output: {1.1=Very Low, 3.9=High} - String Key Double Value Map.
12345678910111213141516val intToPairMap = mutableMapOf(1 to ("ProductA" to 29.99), 2 to ("ProductB" to 39.99))// Add a new entryintToPairMap[3] = "ProductC" to 49.99// Update an existing entryintToPairMap[1] = "ProductA" to 35.99// Remove an entryintToPairMap.remove(2)// Print the mapprintln(intToPairMap)// Output: {1=(ProductA, 35.99), 3=(ProductC, 49.99)}
A real-life example of Map – Student grading system in Kotlin:
I have created a map-based student grading system where the Student’s name is the Key and their grades are the corresponding values.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
fun main() { // Create a mutable map to store student names and their grades val studentGrades = mutableMapOf<String, Int>() // Adding student grades studentGrades["Adam"] = 85 studentGrades["Cris"] = 92 studentGrades["Charlie"] = 78 studentGrades["Peter"] = 90 studentGrades["Mopit"] = 88 // Display all student grades println("Student Grades:") for ((name, grade) in studentGrades) { println("$name: $grade") } // Updating a student's grade studentGrades["Adam"] = 80 println("\nUpdated Grades:") println("Adam: ${studentGrades["Adam"]}") // Removing a student from the map studentGrades.remove("Charlie") println("\nGrades after removing Charlie:") for ((name, grade) in studentGrades) { println("$name: $grade") } // Check if a student exists and retrieve their grade val studentToCheck = "Peter" if (studentToCheck in studentGrades) { println("\n$studentToCheck's grade: ${studentGrades[studentToCheck]}") } else { println("\n$studentToCheck is not in the grade list.") } // Getting the average grade val averageGrade = studentGrades.values.average() println("\nAverage Grade: $averageGrade") } // Output Student Grades: Adam: 85 Cris: 92 Charlie: 78 Peter: 90 Mopit: 88 Updated Grades: Adam: 80 Grades after removing Charlie: Adam: 80 Cris: 92 Peter: 90 Mopit: 88 Peter's grade: 90 Average Grade: 87.5 |
If there is anything in your mind please feel free to ask in the comment section, There are also more functions available of Map in Kotlin’s official documentation. You can read them from HERE. Happy coding.