Set and Map
In this page:
Creating and Using a Set
setOf(...) builds a collection that automatically discards duplicate values, useful whenever uniqueness matters more than order or position.
Example: Creating and Using a Set
fun main() {
val uniqueNumbers = setOf(1, 2, 2, 3, 3, 3)
println(uniqueNumbers)
println("Contains 2: ${uniqueNumbers.contains(2)}")
}
Login to try C/C++/Java/PHP code in the editor
Creating and Using a Map
mapOf(...) builds a read-only collection of key-value pairs, constructed using the infix to function to pair each key with its value.
Example: Creating and Using a Map
fun main() {
val ages = mapOf("Ana" to 30, "Bo" to 25)
println(ages)
println("Ana's age: ${ages["Ana"]}")
}
Login to try C/C++/Java/PHP code in the editor
Handling Missing Map Keys
Looking up a key that doesn't exist with map[key] returns null rather than throwing, so the result is naturally a nullable type that should be handled with ?: or a null check.
Example: Handling Missing Map Keys
fun main() {
val ages = mapOf("Ana" to 30)
val boAge = ages["Bo"] ?: -1
println("Bo's age (or -1 if missing): $boAge")
}
Login to try C/C++/Java/PHP code in the editor
Mutable Sets and Maps
mutableSetOf() and mutableMapOf() create their mutable counterparts, supporting .add() for sets and .put()/map[key] = value for maps after creation.
Example: Mutable Sets and Maps
fun main() {
val tags = mutableSetOf("kotlin", "jvm")
tags.add("android")
tags.add("kotlin") // duplicate, ignored
val scores = mutableMapOf("Ana" to 90)
scores["Bo"] = 85
println(tags)
println(scores)
}
Login to try C/C++/Java/PHP code in the editor
- Expecting a
Setto preserve insertion order like aList; a plainHashSet-backedsetOf()does not guarantee order (thoughLinkedHashSetdoes). - Using square-bracket access on a
Mapfor a missing key and gettingnullunexpectedly instead of an exception, then not handling that null. - Confusing
mapOf()(read-only) withmutableMapOf()when the map actually needs to be modified after creation.
setOf(...)creates a read-onlySetthat automatically removes duplicate values.mapOf(...)creates a read-onlyMapof key-value pairs, built using thekey to valuesyntax.- Accessing a missing key in a
Mapwithmap[key]returnsnullrather than throwing. mutableSetOf()andmutableMapOf()are the mutable counterparts supporting.add()/.put()and removal.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: