Skip to Content
Course content

28: Collections and Sequence Operations

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A few years ago, I was reviewing a pull request from a junior dev who was building a report generator for a fintech app. He had a list of about 50,000 transactions and was applying three different filters and two maps to get the final result. The code looked clean—just a nice chain of Kotlin standard library functions. But when we ran it against a production-sized dataset in the staging environment, the memory usage spiked aggressively, and the app slowed to a crawl. The problem wasn't the logic; it was the fact that every single .filter and .map call was creating a brand new, intermediate List in memory before passing it to the next operation.

The Cost of Intermediate Collections

By default, Kotlin's collection operations are "eager." If you have a list of 100,000 items and you call .filter { ... }, Kotlin iterates through the entire list and allocates a new list for the results. If you immediately chain a .map { ... } after that, Kotlin iterates through that second list and allocates a third list. If your chain is five functions long, you're potentially creating five different versions of your data in the heap.

For small lists, this doesn't matter. In fact, for small datasets, eager evaluation is often faster because there's less overhead. But once you hit a certain scale, or once your transformations become computationally expensive, these intermediate allocations become a massive bottleneck. I usually tell my team: if you're chaining more than two or three operations on a list that could potentially grow, stop and think about your memory footprint.

// This is eager. It creates a new list at every step.
val result = transactions
    .filter { it.amount > 100 }    // List 1 created
    .filter { it.category == "Food" } // List 2 created
    .map { it.id }                 // List 3 created

Switching to Lazy Evaluation with Sequences

This is where Sequence comes in. A Sequence is the Kotlin equivalent of Java Streams. The key difference is that sequences are "lazy." They don't perform any work until you actually ask for the final result (the "terminal operation").

When you call .asSequence(), you're telling Kotlin: "Don't execute these steps yet. Just remember the plan." Instead of processing the whole list at once, a sequence processes one element through the entire chain before moving to the next element. It's like an assembly line rather than a batch process. If you only need the first 10 results, a sequence will stop processing the moment it finds 10 matches, whereas a list would have filtered all 50,000 items first.

// This is lazy. No intermediate lists are created.
val result = transactions.asSequence()
    .filter { it.amount > 100 }
    .filter { it.category == "Food" }
    .map { it.id }
    .toList() // This is the terminal operation that triggers the work

Choosing Your Tool Based on Data Volume

You might be tempted to use asSequence() everywhere just to be safe, but don't. Sequences have a slight overhead because they have to maintain the state of the transformation pipeline. For a list of 20 items, .filter().map() is significantly faster than .asSequence().filter().map().toList().

I follow a simple rule of thumb: use standard collections for small, fixed-size data. Switch to sequences when you're dealing with "big" data (thousands of items), when you have a long chain of operations, or when you're using .take(n) to limit the results. If you can stop the process early, sequences aren't just a performance win—they're a necessity.




📋 Practical Task

Refactoring the High-Volume Inventory Filter

You are working on a warehouse management system. There is a function that processes a massive list of InventoryItem objects to find expensive, fragile items that need special packaging. The current implementation is causing memory spikes in production because it uses eager collection operations on a list of 100,000 items.

Your Task: Refactor the processFragileItems function. Convert the logic to use a Sequence to avoid intermediate list allocations, and ensure you use a terminal operation to return the final result as a List<String>.

data class InventoryItem(val id: String, val price: Double, val isFragile: Boolean, val category: String)

fun processFragileItems(items: List<InventoryItem>): List<String> {
    // CURRENT EAGER IMPLEMENTATION
    return items
        .filter { it.isFragile }
        .filter { it.price > 500.0 }
        .filter { it.category == "Electronics" }
        .map { "Item ID: ${it.id} requires special handling" }
}

// Implement your refactored version here using .asSequence()
Rating
0 0

There are no comments for now.

to be the first to leave a comment.