Part 06 / Topic 3 of 7
Sets: uniqueness as a tool
A Set holds every value at most once — adding a duplicate changes nothing. Reach for a Set
the moment "no duplicates" is the actual requirement, not something you'd otherwise check by hand.
val pincodesServed = setOf("411001", "411004", "411001", "411045")
println("Pincodes served: $pincodesServed")
println("Count: ${pincodesServed.size}") // 3, not 4 -- the repeat was silently dropped
Pincodes served: [411001, 411004, 411045]
Count: 3
contains/in is the main reason to pick a Set over a List for lookups — "have I seen this
already?" reads directly, with no loop of your own:
println("Serves 411004: ${"411004" in pincodesServed}")
println("Serves 560001: ${"560001" in pincodesServed}")
Serves 411004: true
Serves 560001: false
mutableSetOf(...) adds add()/remove(), same shape as MutableList. add() on a value already
present simply does nothing (no exception, just no change):
val vipCustomers = mutableSetOf("Asha", "Ravi")
vipCustomers.add("Meera")
vipCustomers.add("Asha") // already present -- no change
println("VIP customers: $vipCustomers")
vipCustomers.remove("Ravi")
println("After removing Ravi: $vipCustomers")
VIP customers: [Asha, Ravi, Meera]
After removing Ravi: [Asha, Meera]
Real-world example: de-duplicating an existing list is .toSet() away — a common way to turn "every
order placed" into "who actually ordered":
val ordersPlacedBy = listOf("Asha", "Ravi", "Asha", "Meera", "Ravi")
println("Unique customers: ${ordersPlacedBy.toSet()}")
Unique customers: [Asha, Ravi, Meera]
Full program: examples/03_sets.kt.
Done here? The practice set for Part 6 — including the solutions — is on the part page.