Kotlin mutableMapOf

In this guide, we will learn about the Kotlin mutableMapOf() function with lots of examples.

What is mutableMapOf()? 

The mutableMapOf() function is a part of the Kotlin standard library, crafted to create mutable maps. A mutable map is a collection of key-value pairs, akin to regular maps. However, with mutable maps, you can freely add, modify, or remove entries even after their initial creation. 

Basic Syntax:

val mutableMap: MutableMap<KeyType, ValueType> = mutableMapOf(key1 to value1, key2 to value2, ...)

Examples with Outputs

Constructing a Basic Mutable Map

val languages = mutableMapOf("JS" to "JavaScript", "PY" to "Python")
println(languages)  // Output: {JS=JavaScript, PY=Python}
Adding New Entries to the Map

val vehicles = mutableMapOf("C" to "Car", "B" to "Bike")
vehicles["T"] = "Truck"
println(vehicles)  // Output: {C=Car, B=Bike, T=Truck}
Removing Entries from the Map
val elements = mutableMapOf(1 to "Hydrogen", 2 to "Helium", 3 to "Lithium")
elements.remove(3)
println(elements)  // Output: {1=Hydrogen, 2=Helium}
Modifying Existing Map Entries
val grades = mutableMapOf("Alice" to 90, "Bob" to 75)
grades["Alice"] = 95
println(grades)  // Output: {Alice=95, Bob=75}
Checking If a Key Exists

val fruits = mutableMapOf("A" to "Apple", "B" to "Banana")
println("C" in fruits)  // Output: false
Clearing All Entries from the Map
val colors = mutableMapOf("R" to "Red", "G" to "Green", "B" to "Blue")
colors.clear()
println(colors)  // Output: {}

Convert a mutable map to an immutable one

val mutableData = mutableMapOf(1 to "One", 2 to "Two")
val immutableData = mutableData.toMap()

Iterate over a mutableMapOf()

val pets = mutableMapOf("Dog" to "Bark", "Cat" to "Meow")
for ((animal, sound) in pets) {
    println("$animal says $sound")
}
// Output:
// Dog says Bark
// Cat says Meow

Conclusion

mutableMapOf() shines in scenarios where the map's content needs to be dynamically changed, like adding or removing entries based on user input or real-time data. If your map doesn't require alterations post-creation, prefer mapOf() for immutability and associated benefits.

Comments