1. Why pipelines break silently
Pipelines on collections look nice: the chain map → filter → group → sort → take reads almost like an English sentence. But that’s exactly why mistakes in them are tricky: the program can compile successfully and even print something—just not what you intended. Today we’ll practice recognizing these “silent” breakages before they grow into the stage of “why does the report show zero even though I definitely spent money.”
Let’s lock in the basic picture: a pipeline is a sequence of data-shape transformations, and at every step it’s important to remember what exactly gets returned.
flowchart TD
A["List⟨Pair⟨String, Int⟩⟩ (expenses)"] --> B["Normalization (map)"]
B --> C["Filtering (filter)"]
C --> D["Aggregation (groupBy+fold / groupingBy)"]
D --> E["Sorting (sortedByDescending)"]
E --> F["Selection (take)"]
F --> G["Text rendering (StringBuilder)"]
If in this chain you “lost” the result of a step, confused an operation that “returns a new list” with one that “mutates in place,” or hid a side effect inside map, then the pipeline turns into a beautiful but very confident lie.
2. Lost the result of sorted/filter/map
This mistake looks so innocent that you want to justify it: “well, I called sorting—so the list got sorted.” But many collection operations in Kotlin do not mutate the source; they return a new result. For example, sorted() creates a new list, unlike sort() on MutableList, which sorts in place. That’s why you often see pairs of functions: “in-place” and “returns a new collection,” for example sort() vs sorted().
Example: why didn’t the list get sorted?
fun main() {
val amounts = listOf(30, 10, 20)
amounts.sorted() // result is lost
println(amounts) // [30, 10, 20] (nothing changed)
}
Fix: save the result:
fun main() {
val amounts = listOf(30, 10, 20)
val sorted = amounts.sorted()
println(sorted) // [10, 20, 30]
println(amounts) // [30, 10, 20] (the source lives its own life)
}
Mini table: mutates or returns?
It’s convenient to cement the intuition with a small cheat sheet (not cramming—just “so your eye gets used to it”). For collections in Kotlin, the idea that “there’s a pair of functions” is normal practice.
| What we want to do | If the collection is read-only (List) | If the collection is mutable (MutableList) |
|---|---|---|
| Sort | sorted() returns a new list | sort() sorts “in place” |
| Filter | filter() returns a new list | usually filter() also returns a new one; “in-place” filtering is done differently, but that’s a separate story |
| Transform elements | map() returns a new list | map() also returns a new one |
In our practical app (expense tracking) this shows up all the time: you build a report and then “slightly sort the expenses before printing” —and suddenly nothing changes, because the sort wasn’t saved.
3. map for side effects and a Unit list
This mistake appears when your brain thinks, “I need to iterate over the list and do something,” and your hand automatically reaches for map. But semantically, map means “transform each element into a new element and collect a new list.” If inside you do println, then the result of map becomes a list of Unit. And Kotlin honestly hands it back to you.
Example: an anti-pattern
fun main() {
val categories = listOf("food", "taxi")
val result = categories.map { println(it) } // printing = side effect
// food
// taxi
println(result) // [kotlin.Unit, kotlin.Unit]
}
Sometimes students look at [kotlin.Unit, kotlin.Unit] and think it’s some new collection of mysterious units that must be defeated with magic. In reality it’s simpler: println(...) returns Unit, so map collected those “results”—that is, Unit.
Fix: if you’re doing an action rather than building a new collection
The most straightforward path is a plain for:
fun main() {
val categories = listOf("food", "taxi")
for (c in categories) {
println(c) // food, taxi
}
}
You can also use forEach, but in our course it’s often easier to start with for, because it doesn’t hide any magic. The key idea: map is not “to iterate,” it’s “to transform.”
In reports this is especially important: if you print something “inside the pipeline” for debugging, you get side effects that are then hard to remove—and even harder to understand where exactly they occur.
4. groupBy for statistics and when eachCount is better
When you need statistics like “frequency” or “how many times a value occurred,” many people out of habit use groupBy, because it’s familiar. But groupBy returns Map<K, List<V>>: for each key it builds a list of the group’s elements. That’s fine if you really want to work with the group’s list afterward.
But if you only need statistics (for example, “how many expenses in each category” or “how many times a word appears”), those group lists become unnecessary baggage.
Example: category frequencies via groupBy (possible, but a bit heavy)
fun main() {
val categories = listOf("food", "taxi", "food")
val grouped = categories.groupBy { it } // Map<String, List<String>>
val counts = grouped.mapValues { (_, group) -> group.size }
println(counts) // {food=2, taxi=1}
}
Example: the same via groupingBy().eachCount()
groupingBy() gives you a Grouping object, and eachCount() counts elements per group without building the group lists.
fun main() {
val categories = listOf("food", "taxi", "food")
val counts = categories.groupingBy { it }.eachCount()
println(counts) // {food=2, taxi=1}
}
For our expenses app, this means: if you’re producing a report like “how many operations per category,” then eachCount() is not only shorter, but also closer to the meaning of the task.
5. Two sorts in a row and “magic” chains
There’s a special class of “mistakes” where the result is correct, but the code does extra work and becomes hard to read. Sorting is a common example: you sorted by amount, then again by name, then took take(5), then sorted again because “it doesn’t look quite right.”
The problem here isn’t only performance; it’s that the meaning starts to blur: it’s unclear which rule is ultimately the main one.
Let’s look at a typical situation: we have totals per category, and we want top-N. A good idea: sorting should happen once, closer to the “presentation” (i.e., output), rather than being smeared across all the logic.
Example: a questionable chain
fun main() {
val totals = listOf("taxi" to 250, "food" to 200, "books" to 90)
val top = totals
.sortedBy { it.first } // sort by name
.sortedByDescending { it.second } // then by sum (overwrites the idea)
.take(2)
println(top) // [(taxi, 250), (food, 200)] (may “accidentally” match, but the logic is muddy)
}
Yes, Kotlin sorts are stable (we won’t dig into internals here), but even if the result is “fine,” the code doesn’t explain the intention well.
Example: clearer—one sorting rule
fun main() {
val totals = listOf("taxi" to 250, "food" to 200, "books" to 90)
val top = totals
.sortedByDescending { it.second } // primary criterion
.take(2)
println(top) // [(taxi, 250), (food, 200)]
}
If you need “by descending sum, and if equal—by name,” then it’s better to express that as a single criterion (via sortedWith + compareBy). But what matters more here is catching the smell of the problem: “the chain looks like magic.”
6. Extra passes over the data
This mistake isn’t always noticeable on small lists (and on small lists almost everything runs fast). But in reports it shows up unpleasantly: you write “nice” code, and then a report on 100,000 operations starts to lag, and you don’t understand why.
A common reason is several independent passes that could have been combined—or at least made more deliberate. For example, you compute filtered, then separately count, then separately sum, and every time the filtering repeats.
Example: repeating the same filter twice
fun main() {
val amounts = listOf(10, 200, 30, 500)
val countBig = amounts.filter { it >= 100 }.count()
val sumBig = amounts.filter { it >= 100 }.fold(0) { acc, x -> acc + x }
println(countBig) // 2
println(sumBig) // 700
}
Does it work? Yes. Does it do two passes with the same filter? Also yes.
In real life you don’t always have to “optimize,” but you do have to understand what’s happening. Often it’s enough to extract the filtered result into a val, and your code becomes both faster and more readable.
Fix: one filter—two computations
fun main() {
val amounts = listOf(10, 200, 30, 500)
val big = amounts.filter { it >= 100 }
val countBig = big.count()
val sumBig = big.fold(0) { acc, x -> acc + x }
println(countBig) // 2
println(sumBig) // 700
}
In reporting functions this is especially appropriate: intermediate vals provide “stop points” where you can visually check what data you have after a step.
7. Sequence: laziness and the forgotten terminal step
With Sequence, a classic story happens: you read that it’s “faster,” turn on asSequence()—and then mysticism begins. In reality there’s no mysticism: Sequence is lazy. Intermediate operations (map, filter) only describe the steps, and computation actually starts at a terminal operation—for example, toList().
Example: I thought it was already computed
fun main() {
val xs = listOf(1, 2, 3)
val seq = xs.asSequence()
.map { it * 10 }
println(seq) // kotlin.sequences.TransformingSequence@... (not a list!)
}
This isn’t a bug. You printed a pipeline-description object, not the result.
Fix: materialize the result
fun main() {
val xs = listOf(1, 2, 3)
val ys = xs.asSequence()
.map { it * 10 }
.toList()
println(ys) // [10, 20, 30]
}
Important nuance: side effects inside Sequence run later
If inside map you have println, you don’t control the timing of printing as obviously as with a regular list. Printing will happen only when a terminal operation occurs.
fun main() {
val xs = listOf(1, 2, 3)
val seq = xs.asSequence()
.map {
println("mapping $it") // will run later
it * 10
}
println("Before toList()") // Before toList()
val ys = seq.toList()
println("After toList()") // After toList()
println(ys) // [10, 20, 30]
}
This effect is useful for debugging, but harmful if you accidentally mixed computation and output.
8. Map in a report and unstable ordering
When you build a report, it’s very tempting to do println(totalsByCategory) and be happy. But in a real report something else matters more: output must be predictable. Even if you don’t write tests, a person (or you in a week) wants to see the same line order every time.
From a type perspective, everything is logical: Map is not a “list of lines,” it has its own nature. When you need ordering, you usually turn entries into a list and sort explicitly.
Example: rendering a per-category report with explicit sorting
fun renderTotalsByCategory(totals: Map<String, Int>): String {
val rows = totals.entries
.map { it.key to it.value }
.sortedBy { (cat, _) -> cat } // sort by category name
val sb = StringBuilder()
for ((cat, sum) in rows) {
sb.append(cat).append(": ").append(sum).append('\n')
}
return sb.toString()
}
And a small check:
fun main() {
val totals = mapOf("taxi" to 250, "food" to 200, "books" to 90)
print(renderTotalsByCategory(totals))
// books: 90
// food: 200
// taxi: 250
}
In this code we separated “data” and “presentation”: first we create ordered data rows (a list of pairs), and then we assemble the text. This helps not only with order, but also with readability.
9. Mini walkthrough: an expense report and typical failures
Now we’ll take our familiar daily data format: a list of expenses List<Pair<String, Int>>, where first is the category, and second is the amount. What matters is not “writing a perfect report,” but seeing how small mistakes in a pipeline turn the result into something incorrect or strange. This is the kind of practice where your brain stops trusting words and starts trusting types and returned values.
Source data
fun main() {
val expenses = listOf(
" food " to 120,
"FOOD" to 80,
"taxi" to 250,
"books" to 90
)
println(expenses)
// [( food , 120), (FOOD, 80), (taxi, 250), (books, 90)]
}
Mistake #1: forgot normalization before grouping
fun main() {
val expenses = listOf(" food " to 120, "FOOD" to 80)
val totals = expenses
.groupBy { it.first } // " food " and "FOOD" become different keys
.mapValues { (_, items) -> items.fold(0) { acc, x -> acc + x.second } }
println(totals) // { food =120, FOOD=80} (the category is “split”)
}
Why does this happen? Because groupBy() builds keys exactly from what you give it.
Fix: normalize the key before grouping
fun normCategory(s: String): String = s.trim().lowercase()
fun main() {
val expenses = listOf(" food " to 120, "FOOD" to 80)
val totals = expenses
.map { (cat, amount) -> normCategory(cat) to amount }
.groupBy { it.first }
.mapValues { (_, items) -> items.fold(0) { acc, x -> acc + x.second } }
println(totals) // {food=200}
}
Mistake #2: sorted, but lost the result
fun main() {
val totals = listOf("taxi" to 250, "food" to 200, "books" to 90)
totals.sortedByDescending { it.second } // lost the result
println(totals) // [(taxi, 250), (food, 200), (books, 90)] (as it was)
}
It may seem like “it’s already sorted,” as long as the data happens to be in that order. But that’s a trap: sortedByDescending returns a new list, and does not change the original.
Fix: save the result
fun main() {
val totals = listOf("taxi" to 250, "food" to 200, "books" to 90)
val sorted = totals.sortedByDescending { it.second }
println(sorted) // [(taxi, 250), (food, 200), (books, 90)]
}
10. Typical pipeline mistakes
Mistake #1: called sorted()/filter()/map() and didn’t save the result.
This happens because many operations return a new collection rather than changing the old one. The cure is a habit: if the operation is not “in-place,” then you almost always need a val. Hint: MutableList has sort(), and List has sorted().
Mistake #2: using map as “just iterate and do an action.”
If inside map you have println, writing into an external var, or something similar, then you mixed transformation and a side effect. The result is either lost or turns into a list of Unit. Usually it helps to replace it with for and, if needed, separate computation from output.
Mistake #3: using groupBy where you only need statistics.
groupBy creates a Map<K, List<V>>. If you then only take size or just count frequencies, you built unnecessary lists. Often it’s simpler and more semantically honest to use groupingBy().eachCount().
Mistake #4: several sorts in a row “just to be safe.”
The code starts to look like a “ritual”: it seems to work, but it’s unclear why. Usually it’s better to define one sorting rule (or one composite rule), apply it once, and only after that do take(n).
Mistake #5: enabled Sequence and forgot the terminal step.
Intermediate operations on Sequence do not execute by themselves. Until toList() (or another terminal step) happens, you’re holding a “computation plan,” not a result. And if there are side effects inside, they will fire later—at the moment the result is materialized into a collection.
Mistake #6: the report prints a Map without explicit sorting and produces a “floating” line order.
When you build a report for a human, output order is part of the contract. If you need order, turn entries into a list of pairs and sort explicitly, then render the text. This makes the result deterministic and calm.
GO TO FULL VERSION