📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
What is mutableMapOf()?
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}
val vehicles = mutableMapOf("C" to "Car", "B" to "Bike")
vehicles["T"] = "Truck"
println(vehicles) // Output: {C=Car, B=Bike, T=Truck}
val elements = mutableMapOf(1 to "Hydrogen", 2 to "Helium", 3 to "Lithium")
elements.remove(3)
println(elements) // Output: {1=Hydrogen, 2=Helium}
val grades = mutableMapOf("Alice" to 90, "Bob" to 75)
grades["Alice"] = 95
println(grades) // Output: {Alice=95, Bob=75}
val fruits = mutableMapOf("A" to "Apple", "B" to "Banana")
println("C" in fruits) // Output: false
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
Comments
Post a Comment
Leave Comment