Kotlin Collections: Think Transformations, Not Loops
Treat collection operations as a pipeline, not a `for` loop. Each function (`map`, `filter`) transforms data and passes it to the next stage, ideal for turning API data into UI models.
WHY IT EXISTS Traditional for loops are imperative; you tell the computer how to do something step-by-step. This can be verbose and error-prone, mixing business logic with loop management. Functional operations offer a declarative approach: you state what you want the end result to be, leaving the iteration details to the language. This improves code readability and reduces boilerplate.
THE MENTAL MODEL Think of a factory assembly line. A raw list of items enters at one end. The first station (filter) removes items that don't meet a quality check. The next station (map) transforms the remaining items into a new shape. The final station (toList) packages them for use. Each station is a self-contained, predictable function, and you just connect them in a chain.
HOW IT WORKS Kotlin provides higher-order functions as extensions on Iterable. Key operations include: map, which transforms each element into a new one (e.g., User to String); filter, which keeps only elements matching a predicate; forEach, which performs an action on each element; find or first, which locates a single element; and groupBy, which organizes elements into a map. These functions are chained together. For example, users.filter { it.isActive }.map { it.name } first creates a new list of active users, then a second new list containing only their names.
WHEN TO USE IT Use functional operations for most collection transformations where readability is key. They are perfect for preparing data for a UI, like filtering a list of contacts based on a search query and then mapping them to a displayable format. They excel at expressing business logic clearly and concisely for small to medium-sized collections (up to a few thousand items).
WHEN NOT TO USE IT The biggest footgun is performance on large collections. Each intermediate operation in a standard chain (e.g., filter then map) creates a whole new temporary list. On a list with a million items, this is incredibly wasteful. For performance-critical code or very large datasets, either use a traditional for loop for maximum control or convert the collection to a Sequence first with asSequence(). A Sequence processes elements lazily, one by one through the entire chain, avoiding intermediate collections.
ONE CANONICAL EXAMPLE In an Android app, you might get a list of Transaction data objects from an API. To display only the high-value, recent transactions, you would chain operations: transactions.filter { it.isRecent && it.value > 1000 }.map { it.displayString }.toList(). This is far more readable than nested if statements inside a for loop.
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.