Maps and key-based lookup
Maps and key-based lookup
A teacher wants to retrieve a mark by student name rather than by position. A Map associates unique keys with values of a common type. Looking up an absent key returns a nullable value, which allows an explicit missing-student path.
What you’ll learn
- Look up, update and remove a map entry.
- Distinguish absent keys from nullable stored values.
Maps and key-based lookup in the example
Key
Use the lookup identity for one association.
DiyaLookup
A present key supplies its recorded value.
85Missing key
A lookup for Noor has no value.
null
Understand maps and key-based lookup
Kotlin Map reads key-value associations, and MutableMap permits updates. A missing key lookup returns null. Keys should represent the intended identity; use sortedKeys or an explicitly sorted key list when report order is part of the contract. Assigning null does not universally mean removal as it does in some languages.
Connect this to nullable types and safe calls and data classes, equality and copying.
Follow maps and key-based lookup
Save the complete source as Main.kt and use the Kotlin/JVM environment. No separate input file is needed.
Kotlin/JVM · complete program
fun main() {
val scores = mutableMapOf("Diya" to 80, "Saira" to 90)
scores["Diya"] = 85
println(scores["Diya"])
println(scores["Noor"] == null)
scores.remove("Saira")
println(scores.keys.sorted())
}Expected output
85
true
[Diya]Follow the execution
Diya’s value becomes 85 and Noor has no entry. Remove explicitly deletes Saira. The sorted remaining key list prints Diya, independently of any general map implementation’s iteration policy.
Try this in the Kotlin compiler by pasting the complete program.
Practice: Maps and key-based lookup
Your task: How should this program delete Saira’s entry?
Kotlin/JVM · complete program
fun main() {
val scores = mutableMapOf("Diya" to 80, "Saira" to 90)
scores["Diya"] = 85
println(scores["Diya"])
println(scores["Noor"] == null)
scores.remove("Saira")
println(scores.keys.sorted())
}Worked answer
Call scores.remove("Saira"). The removal operation makes the intended action explicit.
Maps and key-based lookup: the important boundary
When values are themselves nullable, a null lookup can mean either a missing key or a stored null; containsKey distinguishes them. Equal names are not always equal student identities.
Check your understanding
Maps and key-based lookup: what to keep in mind
Call scores.remove("Saira"). The removal operation makes the intended action explicit. When values are themselves nullable, a null lookup can mean either a missing key or a stored null; containsKey distinguishes them.
Further reading: official Kotlin documentation for this topic.
Reaching the recap and completing the quizzes are separate milestones.