Kotlin Maps
Key-value pair collections for data storage
πΊοΈ What are Kotlin Maps?
Maps store data as key-value pairs where each key is unique. They're perfect for lookups, dictionaries, and associating related data. Kotlin provides both immutable and mutable map implementations for different use cases.
// Creating a simple map
val ages = mapOf(
"Alice" to 25,
"Bob" to 30,
"Charlie" to 35
)
println("Alice's age: ${ages["Alice"]}")
Output:
Alice's age: 25
Map Features
Key-Value Pairs
Store associated data together
"name" to "John"
Fast Lookups
Quickly find values by key
map["key"]
Unique Keys
Each key appears only once
map.keys.distinct()
Mutable Maps
Add, remove, and update entries
mutableMapOf()
πΉ Creating Maps
Different ways to create and initialize maps:
// Immutable map
val countries = mapOf(
"US" to "United States",
"UK" to "United Kingdom",
"CA" to "Canada"
)
// Mutable map
val scores = mutableMapOf(
"Alice" to 95,
"Bob" to 87
)
// Empty maps
val emptyMap = emptyMap<String, Int>()
val emptyMutable = mutableMapOf<String, String>()
println("Countries: $countries")
println("Scores: $scores")
println("US: ${countries["US"]}")
println("Map size: ${countries.size}")
Output:
Countries: {US=United States, UK=United Kingdom, CA=Canada}
Scores: {Alice=95, Bob=87}
US: United States
Map size: 3
πΉ Map Operations
Access, modify, and work with map data:
val inventory = mutableMapOf(
"apples" to 50,
"bananas" to 30,
"oranges" to 25
)
// Access values
val appleCount = inventory["apples"]
val grapeCount = inventory.getOrDefault("grapes", 0)
// Add and update
inventory["grapes"] = 15
inventory.put("pears", 20)
// Remove items
inventory.remove("bananas")
// Check existence
val hasApples = "apples" in inventory
val hasKeys = inventory.containsKey("oranges")
println("Apples: $appleCount")
println("Grapes: $grapeCount")
println("Updated inventory: $inventory")
println("Has apples: $hasApples")
Output:
Apples: 50
Grapes: 0
Updated inventory: {apples=50, oranges=25, grapes=15, pears=20}
Has apples: true
πΉ Iterating Over Maps
Loop through keys, values, or entries:
val grades = mapOf(
"Math" to 'A',
"Science" to 'B',
"History" to 'A',
"English" to 'C'
)
// Iterate over entries
println("All grades:")
for ((subject, grade) in grades) {
println("$subject: $grade")
}
// Iterate over keys
println("\nSubjects:")
for (subject in grades.keys) {
println("- $subject")
}
// Iterate over values
println("\nGrades received:")
for (grade in grades.values) {
println("Grade: $grade")
}
// Filter and transform
val excellentSubjects = grades.filter { it.value == 'A' }
println("\nExcellent subjects: $excellentSubjects")
Output:
All grades:
Math: A
Science: B
History: A
English: C
Subjects:
- Math
- Science
- History
- English
Excellent subjects: {Math=A, History=A}