Collections and sequences

How Kotlin lists, sets and maps really behave, what read-only means, and when a lazy sequence is better than a list. About 20 minutes.

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, sortedBy chains 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:

TypeRead-only interfaceMutable interfaceDefault from the builder
Ordered, duplicates allowedListMutableListlistOf, mutableListOf (an ArrayList)
Unique itemsSetMutableSetsetOf (keeps insertion order)
Key to valueMapMutableMapmapOf (keeps insertion order)
Lazy, one item at a timeSequencenoneasSequence(), sequenceOf, generateSequence

Notes

  • List is a read-only view, not an immutable object. If someone else holds the MutableList, your List changes too. toList() makes a real copy.
  • Operations like map and filter on 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.
  • sorted and sortedBy are stateful steps that need every item. A sequence must read everything before it can give the first result, so you lose the early exit. distinct also keeps state (the items it has seen), but it still passes items on one by one.
  • Sequences are not always faster. For small lists, map and filter on a collection are inline and 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] returns null if missing. getValue(key) throws.
    • first() throws on an empty list. firstOrNull() does not.
    • associateBy keeps the last item when two share a key.
  • Changing a list while you loop over it usually throws ConcurrentModificationException. Use removeAll { } or build a new list with filter.
  • In Compose, changing a plain mutableListOf inside mutableStateOf does not update the UI, because it is the same object. Use mutableStateListOf, 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 call

Run 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

The contact search that froze the keyboard
  • 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, map and sortedBy on the whole list. The work ran on the main thread, because viewModelScope uses Dispatchers.Main.immediate by 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.
The fix
  1. 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.
  2. If the data is in Room, filter and sort in the query with LIKE and LIMIT. The database is built for this.
  3. If it must stay in memory: debounce the input, run the work on Dispatchers.Default, and use a sequence with take so it stops after enough matches.
  4. Remember that sortedBy still reads everything. Sort in the database, or sort only the small final page.
The crash that only happened during sync
  • A repository kept private val _items = mutableListOf<Item>() and exposed it as val items: List<Item> get() = _items.
  • A background sync added items while the UI looped over items. Crash reports showed an occasional ConcurrentModificationException. It was rare and impossible to reproduce by hand.
  • Cause: the List was only a view of the same mutable list, shared between two threads.
The fix
  • 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 List as immutable. The List type only blocks changes through that reference. Copy with toList() 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 sortedBy first and expecting take(5) to be cheap. The sort reads and orders all items before take runs.
  • Removing items inside a for loop. Use removeAll { } or filter into a new list.
  • Calling first(), single() or getValue() on data that may be missing. They throw. Use the OrNull versions 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:

  1. Create a list of 100,000 numbers with (1..100_000).toList().
  2. Write a chain: keep even numbers, multiply by 3, take the first 5. Write it once on the list and once with asSequence().
  3. Add a counter in each lambda and print how many times each lambda ran in both versions.
  4. Add sortedDescending() before take(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.

Next: Scope functions