Collections and sequences
Why it matters
- Almost every screen turns a list of data into a list of UI items. Collection code is in every pull request.
- "Read-only" is not "immutable". This one fact causes crashes and stale UI in real apps.
- Long
filter,map,sortedBychains on big lists cause jank that only shows on slow phones. - "List vs Sequence" is a common Kotlin interview question, and most answers stop at "sequences are lazy".
The simple explanation
Think of a photo album at a shop counter.
- A List is the album: photos in order, and you can see the same photo twice.
- A Set is a box of unique photos: no duplicates.
- A Map is an index card file: look up a card by its key.
- A read-only album is one you are not allowed to change. But the shop owner may still hold the same album and add photos. You would see them appear.
- An eager chain is a worker who finishes step 1 on all photos, then step 2 on all photos, and carries a new stack each time.
- A sequence is a worker who takes one photo through all steps, then picks the next. He can stop as soon as you say "enough".
The real names:
| Type | Read-only interface | Mutable interface | Default from the builder |
|---|---|---|---|
| Ordered, duplicates allowed | List | MutableList | listOf, mutableListOf (an ArrayList) |
| Unique items | Set | MutableSet | setOf (keeps insertion order) |
| Key to value | Map | MutableMap | mapOf (keeps insertion order) |
| Lazy, one item at a time | Sequence | none | asSequence(), sequenceOf, generateSequence |
Notes
Listis a read-only view, not an immutable object. If someone else holds theMutableList, yourListchanges too.toList()makes a real copy.- Operations like
mapandfilteron a collection are eager. Each step builds a new collection. - On a
Sequence, intermediate steps (filter,map,take) do nothing until a terminal call (toList,first,sum,forEach) asks for items. - A sequence sends one element through the whole chain before it takes the next. That is why
first()can stop early. sortedandsortedByare stateful steps that need every item. A sequence must read everything before it can give the first result, so you lose the early exit.distinctalso keeps state (the items it has seen), but it still passes items on one by one.- Sequences are not always faster. For small lists,
mapandfilteron a collection areinlineand cheap. Sequence steps keep lambda objects and iterators. - Use a sequence when the list is large, the chain has several steps, and it can stop early (
first,take,any). - Lookups are different:
map[key]returnsnullif missing.getValue(key)throws.first()throws on an empty list.firstOrNull()does not.associateBykeeps the last item when two share a key.
- Changing a list while you loop over it usually throws
ConcurrentModificationException. UseremoveAll { }or build a new list withfilter. - In Compose, changing a plain
mutableListOfinsidemutableStateOfdoes not update the UI, because it is the same object. UsemutableStateListOf, or replace the list with a new one.
Code example
An order summary: total per customer, best customers first. Plain collections are right here, because the list is small and every step needs all items.
data class Order(val id: Int, val customer: String, val total: Int, val paid: Boolean)
fun topCustomers(orders: List<Order>, limit: Int): List<String> =
orders
.filter { it.paid } // keep paid orders
.groupBy { it.customer } // Map of customer to orders
.mapValues { (_, list) -> list.sumOf { it.total } } // total per customer
.entries
.sortedByDescending { it.value } // best first
.take(limit)
.map { it.key }
// Big list, early exit possible: a sequence stops after 20 matches.
fun firstMatches(contacts: List<String>, query: String): List<String> =
contacts.asSequence()
.filter { it.contains(query, ignoreCase = true) }
.take(20)
.toList() // terminal callRun the difference between the two styles. Watch the order of the printed lines.
fun main() {
val numbers = listOf(1, 2, 3, 4, 5, 6)
println("List (eager):")
val a = numbers
.filter { println(" filter " + it); it % 2 == 0 }
.map { println(" map " + it); it * 10 }
.first()
println("result " + a)
println("Sequence (lazy):")
val b = numbers.asSequence()
.filter { println(" filter " + it); it % 2 == 0 }
.map { println(" map " + it); it * 10 }
.first()
println("result " + b)
// Read-only is a view, not a copy.
val inner = mutableListOf(1, 2)
val view: List<Int> = inner
val copy: List<Int> = inner.toList()
inner.add(3)
println("view = " + view) // [1, 2, 3]
println("copy = " + copy) // [1, 2]
}In production
- Users typed in a search box over a very large contact list. Letters appeared late and the screen stuttered on mid-range phones.
- Cause: on every keystroke the ViewModel ran
filter,mapandsortedByon the whole list. The work ran on the main thread, becauseviewModelScopeusesDispatchers.Main.immediateby default. Each step also allocated a new list, so the garbage collector ran often. - Developers saw nothing on their fast phones with a small set of test contacts.
- Reproduce it with a debug build that has tens of thousands of fake contacts, and record a CPU profile or a Perfetto trace while typing. The time is in the list steps and in GC.
- If the data is in Room, filter and sort in the query with
LIKEandLIMIT. The database is built for this. - If it must stay in memory: debounce the input, run the work on
Dispatchers.Default, and use a sequence withtakeso it stops after enough matches. - Remember that
sortedBystill reads everything. Sort in the database, or sort only the small final page.
- A repository kept
private val _items = mutableListOf<Item>()and exposed it asval items: List<Item> get() = _items. - A background sync added items while the UI looped over
items. Crash reports showed an occasionalConcurrentModificationException. It was rare and impossible to reproduce by hand. - Cause: the
Listwas only a view of the same mutable list, shared between two threads.
- Keep the state in a
MutableStateFlow<List<Item>>and replace the whole list on each change, for example_items.update { it + newItem }. Readers always get a list that never changes again. - Reproduce with a test that adds items on one thread while another loops, repeated many times. Before the fix it fails within a few runs. After the fix readers loop over a snapshot that nobody changes, so it cannot throw.
Common mistakes
- Treating
Listas immutable. TheListtype only blocks changes through that reference. Copy withtoList()when you need a snapshot. - Using a sequence for a three-item list. The setup costs more than it saves. Measure before you switch.
- Putting
sortedByfirst and expectingtake(5)to be cheap. The sort reads and orders all items beforetakeruns. - Removing items inside a
forloop. UseremoveAll { }orfilterinto a new list. - Calling
first(),single()orgetValue()on data that may be missing. They throw. Use theOrNullversions when empty is a normal case. - Mutating a list kept in Compose state. The UI does not notice. Replace it with a new list.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between List and MutableList?”
“When would you use a Sequence instead of a List?”
“What happens if you remove items from a list while looping over it?”
“What does groupBy return and how is it different from associateBy?”
Quiz
val a = mutableListOf(1, 2); val b: List<Int> = a; a.add(3). What is b now?
Which step in a sequence chain must read all elements before it can give its first result?
You call remove inside a for loop over the same MutableList. What can happen?
Two users share an email. You call users.associateBy { it.email }. What does the map hold for that email?
0 of 4 answered
Mini task
In a plain Kotlin file or the Playground above:
- Create a list of 100,000 numbers with
(1..100_000).toList(). - Write a chain: keep even numbers, multiply by 3, take the first 5. Write it once on the list and once with
asSequence(). - Add a counter in each lambda and print how many times each lambda ran in both versions.
- Add
sortedDescending()beforetake(5)in both versions and print the counters again.
You are done when you can explain why the sequence counters were far smaller than the list counters in step 3, and why they became the same as the list counters in step 4.