The Analogy: The Pass at a Busy Diner
At the hot end of a busy diner stands the pass, the counter where the expediter marshals a whole service, and three quite different record-keeping devices sit within arm's reach. The first is the order rail: a long steel bar where paper tickets are clipped in the exact order they arrive off the printer. The tenth ticket of the night hangs after the ninth and before the eleventh, the same dish can appear on ticket after ticket, and the expediter can say "fire the third ticket" and mean one precise slip. The rail is about sequence and position, and it happily holds ten identical steak tickets in a row.
The second device is the sold-out slate, what the trade calls the eighty-six board. When the kitchen runs out of oysters the cook chalks OYSTER on the slate, and from then on the only question anyone asks it is whether a word is up there. Chalking OYSTER a second time changes nothing -- it is already on the board -- and the slate has no notion of which item was crossed off first or how many portions were lost. It answers one question, membership, and answers it the same whether you asked once or ten times.
The third device is the table board: a grid of numbered hooks, one per table, each holding the running chit for that table. To find what table seven is drinking you go straight to hook seven; you never scan the board in order, because the hooks are arranged by table number, not by time of arrival. Hang a fresh chit on an occupied hook and it replaces whatever was there, because a table has one running chit, not a pile. The board is about looking a value up by its key, quickly and directly.
The trouble starts the moment someone asks a device the question it was never built to answer. Ask the table board for "the next order" and it has nothing to say, because hooks keyed by table have no first or next. Worse, read the eighty-six slate to decide how many steaks to cook and you will cook far too few, because the slate records only that steak is a dish in play, never that three tables ordered it. Each device is precise about one thing and silent -- or quietly wrong -- about the others, and the cost of mixing them up is plates that never reach the table.
Syntax or Core Structure
Kotlin gives you three matching collection types. A List is the order rail: ordered, indexed, duplicates allowed. A Set is the slate: membership only, duplicates collapse. A Map is the table board: values looked up by a unique key. The plainest builders are listOf, setOf and mapOf, and each pairs a key to a value in a map with the to word.
fun main() {
val orders = listOf("steak", "soup", "steak", "pie")
val soldOut = setOf("soup", "soup", "oyster")
val tables = mapOf(3 to "steak", 7 to "pie")
println(orders[2])
println(orders.size)
println("oyster" in soldOut)
println(soldOut.size)
println(tables[7])
println(tables[9])
}
Output:
steak
4
true
2
pie
null
Read the results against the three devices. orders[2] is the ticket at index 2 -- the third, counting from zero -- which is the second steak; the list keeps both steaks and its size is 4. The set was built with soup twice, but the duplicate collapses, so soldOut.size is 2, and "oyster" in soldOut asks the membership question and gets true. The map looks up by key: tables[7] is pie, and tables[9] is null because no hook is labelled 9. That trailing null is the single most important habit to build: a map index returns a nullable value.
Technical Depth: Read-only Views and Mutable Backing
Three types, two flavours each
Every collection type comes in a read-only interface and a mutable one. The read-only builder gives you something you can query but not change; the mutable builder adds add, remove and index assignment.
| Type | Read-only builder | Mutable builder | Ordered? | Duplicates? | Looked up by |
|---|---|---|---|---|---|
| List | listOf | mutableListOf | yes, by index | yes | Int index |
| Set | setOf | mutableSetOf | insertion order | no | membership |
| Map | mapOf | mutableMapOf | insertion order | keys unique | key |
The default setOf and mapOf are backed by a LinkedHashSet and LinkedHashMap, so they iterate in insertion order -- the order you added things. The unordered hashSetOf and hashMapOf exist too, and they make no order promise at all. When printed output must be stable, stay with the linked defaults, which is what every example here does.
Read-only is a view, not a guarantee
A read-only List is not the same as an immutable list. It is one interface onto an object that may still be a MutableList underneath, and anyone holding the mutable reference can change what your read-only reference sees.
fun main() {
val backing = mutableListOf("a", "b")
val readOnly: List<String> = backing
backing.add("c")
println(readOnly)
println(readOnly.size)
}
Output:
[a, b, c]
3
Nothing was added through readOnly, yet it now reports three elements, because readOnly and backing are the same object seen through two interfaces. Read-only means "you cannot mutate through this reference," not "this can never change." To hand out a genuinely independent snapshot, copy with toList, which builds a new list the caller cannot reach back into.
Transformations return new collections
The workhorse functions -- filter, map, sum and their kin -- never modify the receiver. Each returns a fresh read-only collection, so you must use the return value.
fun main() {
val nums = listOf(1, 2, 3, 4, 5, 6)
println(nums.filter { it % 2 == 0 })
println(nums.map { it * it })
println(nums.sum())
println(nums)
}
Output:
[2, 4, 6]
[1, 4, 9, 16, 25, 36]
21
[1, 2, 3, 4, 5, 6]
filter keeps the even numbers, map squares every element, and sum folds them to 21, but the final line proves nums is untouched: it still holds all six originals. Every transformation is a new rail of tickets, not an edit to the old one, which is why a call whose result you discard has done nothing useful.
Counting without losing multiplicity
The slate-versus-count distinction has a direct answer in the standard library. groupingBy followed by eachCount turns a list into a map of element to occurrences, keeping every count that a set would throw away.
fun main() {
val dishes = listOf("steak", "soup", "steak", "pie", "steak")
val counts = dishes.groupingBy { it }.eachCount()
println(counts)
println(counts["steak"])
println(dishes.toSet().size)
println(dishes.size)
}
Output:
{steak=3, soup=1, pie=1}
3
3
5
The counts map records that steak was ordered three times, soup and pie once each, and it iterates in first-encounter order because eachCount builds a LinkedHashMap. The two middle lines look alike but ask different questions: counts["steak"] is 3 because steak appeared three times, while dishes.toSet().size is 3 because there are three distinct dishes. The last line, dishes.size of 5, is the total number of orders. A set can give you the 3 distinct kinds; only a count can give you the 5 plates.
Real World Example: Tallying a Service at the Pass
The expediter wants three numbers at the end of a rush: how many orders were refused because a dish was eighty-sixed, how many plates the kitchen must cook, and a per-table count. All three collection types earn their place -- a list of incoming orders, a set of sold-out dishes, and a map of counts per table.
fun main() {
val orders = listOf(
3 to "steak",
7 to "soup",
3 to "steak",
7 to "pie",
12 to "steak",
7 to "soup"
)
val soldOut = setOf("soup")
val served = mutableListOf<String>()
val perTable = mutableMapOf<Int, Int>()
var refusals = 0
for ((table, dish) in orders) {
if (dish in soldOut) {
refusals++
continue
}
served.add(dish)
perTable[table] = perTable.getOrDefault(table, 0) + 1
}
val platesToCook = served.toSet().size
val actualPlates = served.size
println("refusals: " + refusals)
println("plates to cook (flawed): " + platesToCook)
println("plates actually ordered: " + actualPlates)
println("distinct dishes: " + served.toSet())
for ((table, count) in perTable) {
println("table " + table + ": " + count)
}
}
Output:
refusals: 2
plates to cook (flawed): 2
plates actually ordered: 4
distinct dishes: [steak, pie]
table 3: 2
table 7: 1
table 12: 1
The loop destructures each order into table and dish. The sold-out check is a set membership test -- dish in soldOut -- and the two soup orders are refused, so refusals is 2. Every accepted dish is appended to the served list, which keeps duplicates, and perTable counts orders per table through getOrDefault, the idiom that reads the running count or starts at zero. Because perTable is a mutableMapOf (a LinkedHashMap), it prints in insertion order: table 3, then 7, then 12.
The per-table figures are exactly right. Table 3 ordered two steaks, table 7 one pie (its two soups were refused), table 12 one steak -- four accepted plates in all, which actualPlates reports as the size of the served list. The map counted correctly because counting is precisely what a Map<Int, Int> is for.
The headline "plates to cook" line, however, is wrong, and it is wrong in the way the eighty-six slate is wrong. It was computed as served.toSet().size: the code converted the served dishes to a set before counting, collapsing the three steaks into one. The kitchen is told to cook 2 plates when 4 were ordered, and two tables go hungry. A Set answers "which dishes appeared," never "how many of each," and using it where multiplicity matters silently discards the count.
This is the real design flaw in the code above, and it is deliberate: the distinct dishes line is a legitimate use of toSet, but reusing that set to size the cook order confuses "how many kinds" with "how many plates." A second, smaller weakness sits alongside it -- the sold-out test is case-sensitive, so an order for Soup with a capital S would slip past soldOut and be served -- and the code also rebuilds served.toSet() twice where one local would do. The headline count is the fault that reaches the customer, and it traces entirely to reaching for the wrong collection type for the question being asked.
Common Mistakes
- Treating
listOf/setOf/mapOfas deeply immutable. They return read-only interfaces, not frozen data. If the underlying object is a mutable collection reachable through another reference, it can still change under you. Copy withtoList/toSet/toMapwhen you need a real snapshot.
- Calling
addorremoveon a read-only collection. AlistOfresult has noadd; the code will not compile. Reach formutableListOfwhen you genuinely need to modify the collection in place.
- Using a
Setwhere you needed counts. Converting to a set collapses duplicates, so any multiplicity is lost. When "how many of each" matters, use aMap<T, Int>orgroupingBy { it }.eachCount(), as the flawed plate count above shows.
- Relying on order from
hashSetOforhashMapOf. Those make no ordering promise. Only the defaultsetOf/mapOf(linked) iterate in insertion order; if you print from a hash-based collection the order can differ between runs and platforms.
- Forgetting a map index is nullable.
map[key]returnsnullfor an absent key, somap[key].lengthfails to compile or throws once made non-null carelessly. UsegetOrElse,getOrDefault, or a null check.
- Indexing a list out of bounds.
list[list.size]throwsIndexOutOfBoundsException; the last valid index issize - 1. UsegetOrNullwhen the index might be past the end.
- Mutating a collection while iterating it. Adding to or removing from a list inside its own
forloop raisesConcurrentModificationException. Collect changes separately, or iterate a copy, or useremoveAll/retainAll.
- Passing duplicate keys to
mapOf.mapOf(1 to "a", 1 to "b")keeps only the last pair, silently. If two sources can supply the same key, decide the merge rule explicitly rather than letting the later value win by accident.
- Discarding the result of a transformation.
filterandmapreturn new collections and never mutate the receiver, so a call whose result you ignore accomplishes nothing. Assign or chain the returned value.
Best Practices
- Default to read-only
listOf/setOf/mapOf, and introduce a mutable variant only at the point where you actually add or remove elements.
- Choose the type by the question you will ask: position and duplicates point to a
List, membership and uniqueness to aSet, and keyed lookup to aMap.
- Reach for
getOrElse,getOrNullorgetOrDefaultinstead of bare[]whenever a key or index might be absent, so a miss is handled rather than crashing.
- Prefer the standard transformations --
filter,map,associate,groupingBy-- over hand-written loops, and always bind their return values.
- When counts matter, model them with a
Map<T, Int>oreachCount, and never lean on aSetto tell you how many.
- Keep insertion order explicit: use the linked defaults when order is meaningful, and choose
hashSetOf/hashMapOfonly when you truly do not care.
- Copy to an immutable collection with
toList/toSet/toMapat API boundaries, so callers cannot mutate your internal state through a shared reference.
- Iterate maps by destructuring entries, as in
for ((key, value) in map), and never modify a collection inside a loop that is walking it.
Practice Exercises
- Given
listOf("red", "blue", "red", "green", "blue", "red"), print both the number of distinct colours and the total number of entries, and explain in a comment why the two numbers differ.
- Build a word-frequency
Map<String, Int>from a list of words usinggetOrDefault, then print each word and its count in insertion order. Confirm a repeated word raises its count rather than adding a new entry.
- Reproduce the read-only leak: create a
mutableListOf, assign it to aListreference, mutate the backing list, and print the read-only view to show it changed. Then defend the view withtoListand show it no longer changes.
- Rewrite the diner pass so
platesToCookequals the true number of plates ordered, while still reporting the distinct dishes separately. Decide which value should come from the list and which from the set.