1. Why post-processing results is needed
When you first get a result from groupBy or eachCount, you get this feeling: “Oh, there’s the data! Now I’ll just do println(map) —and done.” And yes, technically that will produce output. But if you’ve ever read server logs on a Friday evening (when you just want to exist), you know: “output” and “report” are two very different psychological states.
Post-processing is the step where we solve two problems: what to turn the values into (for example, list → list size), and in what order to present the result (by key, by frequency, top‑N). Ideally, we also make the output convenient: align columns, add headers, and make the report readable by humans—not just by the compiler.
Let’s imagine we continue our console mini-app with a list of expenses (we keep them in memory, without classes and without a database—for now everything is honestly simple). Let an expense be a pair (category, amount):
fun main() {
val expenses = listOf(
"food" to 120,
"food" to 80,
"taxi" to 250,
"books" to 600,
"taxi" to 140
)
println(expenses) // [(food, 120), (food, 80), (taxi, 250), (books, 600), (taxi, 140)]
}
The list looks fine. But as soon as we want a “report by category,” real life begins: we need groupings, counters, sorting—and only then text.
How to choose: eachCount() or groupBy().mapValues { size }
When you see code like this:
val counts = list.groupBy { key }.mapValues { it.value.size }
a reasonable question comes up: “Why do we need eachCount at all if we can do it like that?” And conversely: “Why group into lists if we only need numbers?”
To avoid confusion, it helps to keep a small comparison table in mind:
| Task | Tool | What you get | When it’s convenient |
|---|---|---|---|
| Show details inside each group | |
|
When you will actually iterate over the elements of the group |
| Count “how many elements” per key | |
|
When you do not need the group’s element list at all |
You already have , but now you want a summary |
|
|
When you don’t want to rebuild the pipeline from scratch |
So eachCount() is the more direct path to counters. And mapValues { size } is a life preserver when you already have groups and want to “squeeze” summary numbers out of them.
2. mapValues: transforming map values
When you use groupBy, you almost inevitably get a map whose values are lists: Map<K, List<T>>. That’s logical: a group is a set of elements. But a report often doesn’t want the entire set from a group—it wants a derived value: group size, average, list of names, first/last, and so on.
For such transformations there is mapValues: a function that keeps keys as they are but changes values. And it’s a direct continuation of the idea of “collection transformation chains”: most operations create a new result and do not mutate the original object.
The most common scenario: “I want the group size”
Let’s group expenses by category:
fun main() {
val expenses = listOf(
"food" to 120,
"food" to 80,
"taxi" to 250,
"books" to 600,
"taxi" to 140
)
val byCategory: Map<String, List<Pair<String, Int>>> =
expenses.groupBy { it.first }
println(byCategory["taxi"]) // [(taxi, 250), (taxi, 140)]
}
Now we want a “category → number of entries” map:
fun main() {
val expenses = listOf(
"food" to 120,
"food" to 80,
"taxi" to 250,
"books" to 600,
"taxi" to 140
)
val countsByCategory: Map<String, Int> = expenses
.groupBy { it.first }
.mapValues { entry -> entry.value.size }
println(countsByCategory) // {food=2, taxi=2, books=1}
}
Here it’s important to feel the mechanics: mapValues receives an entry (a key+value pair), and entry.value is that list of elements in the group, while size is simply its length.
If it’s easier for you to read via destructuring, you can do this:
fun main() {
val expenses = listOf("food" to 120, "food" to 80, "taxi" to 250)
val countsByCategory = expenses
.groupBy { it.first }
.mapValues { (_, group) -> group.size }
println(countsByCategory) // {food=2, taxi=1}
}
mapKeys is nearby, but we don’t need it today
Sometimes you want to “fix the keys” (for example, convert them to lowercase). For that there is mapKeys, but today our focus is specifically on post-processing grouping results, and there you more often change the value: list → number, list → string, number → string, and so on.
3. Sorting: working with entries
After counting frequencies, the second pain for a beginner developer appears: “I want to print it nicely: most frequent categories first.” And then a typical life scene happens: you try to “sort a Map,” the compiler looks at you with mild sadness, and you realize that a Map is not an “ordered list of lines,” but a key → value structure.
The correct move: for sorting, we almost always take entries (the set of key/value records) and turn it into a list, which can then be sorted and printed in the desired order.
Sorting by key
fun main() {
val counts = mapOf("taxi" to 2, "food" to 5, "books" to 1)
val sortedByKey = counts.entries.sortedBy { it.key }
for (e in sortedByKey) {
println("${e.key} -> ${e.value}")
// books -> 1
// food -> 5
// taxi -> 2
}
}
Here we sort by it.key. This is convenient for a “reference” report: everything is alphabetical and easy to scan.
Sorting by value in descending order
fun main() {
val counts = mapOf("taxi" to 2, "food" to 5, "books" to 1)
val sortedByCountDesc = counts.entries.sortedByDescending { it.value }
for (e in sortedByCountDesc) {
println("${e.key} -> ${e.value}")
// food -> 5
// taxi -> 2
// books -> 1
}
}
Top‑N via take(n)
After sorting, it’s easy to select the first N records:
fun main() {
val counts = mapOf("taxi" to 2, "food" to 5, "books" to 1, "games" to 4)
val top2 = counts.entries
.sortedByDescending { it.value }
.take(2)
println(top2.map { it.key to it.value }) // [(food, 5), (games, 4)]
}
take(n) is the basic “take the first N elements” operation on a list.
4. Preparing output: strings and StringBuilder
Sorting and mapValues give us a data structure, but the “final report form” is already a string (or a set of strings). And here you really don’t want to glue everything together with one huge println(...); instead, make the code readable: prepare the report lines separately and print them separately.
This is especially useful in our console app: today you print to the console, tomorrow you’ll want to return a string from a function, and the day after tomorrow (in the distant bright future) write it to a file. If the logic of building strings is separated, life is easier.
List of strings → join via joinToString
fun main() {
val counts = mapOf("food" to 5, "taxi" to 2, "books" to 1)
val lines = counts.entries
.sortedByDescending { it.value }
.map { "${it.key}: ${it.value}" }
println(lines.joinToString(separator = "\n"))
// food: 5
// taxi: 2
// books: 1
}
This is already pretty good: readable and predictable. But sometimes you need more control: a header, numbering, alignment.
StringBuilder: when the report is a multi-line document
We’ve already used StringBuilder before to build large strings without endless concatenation. And a nice Kotlin bonus: StringBuilder has convenient extension functions like appendLine, which make building multi-line text almost “literary.”
Let’s build a simple report with a header:
import kotlin.text.appendLine
fun main() {
val counts = mapOf("food" to 5, "taxi" to 2, "books" to 1)
val report = StringBuilder()
.appendLine("Expenses by category (count)")
.appendLine("---------------------------")
.apply {
for (e in counts.entries.sortedByDescending { it.value }) {
appendLine("${e.key}: ${e.value}")
}
}
.toString()
println(report)
// Expenses by category (count)
// ---------------------------
// food: 5
// taxi: 2
// books: 1
}
Note: we’re not discussing scope functions as a topic today, but you can think of apply here simply as “a handy block to append to the builder.” If it’s still easier for you, you can do it without apply:
import kotlin.text.appendLine
fun main() {
val counts = mapOf("food" to 5, "taxi" to 2)
val sb = StringBuilder()
sb.appendLine("Report")
for (e in counts.entries.sortedByDescending { it.value }) {
sb.appendLine("${e.key}: ${e.value}")
}
println(sb.toString())
// Report
// food: 5
// taxi: 2
}
Aligning columns via padEnd and padStart
Sometimes a report becomes much easier to read if numbers line up under numbers. For that it’s convenient to use padEnd/padStart.
import kotlin.text.appendLine
fun main() {
val counts = mapOf("food" to 12, "taxi" to 2, "books" to 100)
val sb = StringBuilder()
sb.appendLine("Category Count")
sb.appendLine("---------------------")
for (e in counts.entries.sortedByDescending { it.value }) {
val category = e.key.padEnd(14)
val count = e.value.toString().padStart(5)
sb.appendLine("$category$count")
}
println(sb.toString())
// Category Count
// ---------------------
// books 100
// food 12
// taxi 2
}
This is not “cosmetics for cosmetics’ sake.” It’s real care for your future self: when the report is large, alignment reduces cognitive load.
5. Practical example: a category report
Now let’s make a cohesive piece of logic that resembles a real project step: we have a list of expenses, and we want to produce a report “how many entries per category” in sorted form.
First, the data-preparation function. We won’t complicate the model: still Pair<String, Int>.
fun buildCategoryCounts(expenses: List<Pair<String, Int>>): Map<String, Int> {
return expenses
.groupBy { (category, _) -> category.trim().lowercase() }
.mapValues { (_, group) -> group.size }
}
Now the function that turns the map into nice text:
import kotlin.text.appendLine
fun formatCategoryCounts(counts: Map<String, Int>, topN: Int): String {
val sorted = counts.entries
.sortedByDescending { it.value }
.take(topN)
val sb = StringBuilder()
sb.appendLine("Top categories by number of expenses")
sb.appendLine("-----------------------------------")
for ((category, count) in sorted) {
sb.appendLine("${category.padEnd(15)} ${count.toString().padStart(4)}")
}
return sb.toString()
}
And finally, main, which demonstrates the whole pipeline:
fun main() {
val expenses = listOf(
" Food " to 120,
"food" to 80,
"taxi" to 250,
"BOOKS" to 600,
"taxi" to 140,
"food" to 30
)
val counts = buildCategoryCounts(expenses)
val report = formatCategoryCounts(counts, topN = 3)
println(report)
// Top categories by number of expenses
// -----------------------------------
// food 3
// taxi 2
// books 1
}
Here we did exactly what we talked about: post-processing the results of grouping transforms data into a form suitable for human reading. And yes, that human is you one week from now.
6. Common mistakes when post-processing a Map
Mistake #1: expecting mapValues to “modify the map in place.”
Beginners often think: “I called mapValues, so the map got updated.” But most collection operations in Kotlin return a new result, and the original collections are not touched. So if you did counts.mapValues{...} and didn’t store the result anywhere, you just computed into the void—as if you wrote a report and forgot to click “Save.”
Mistake #2: trying to sort a Map instead of entries.
Sorting is an operation on an ordered sequence. A Map by itself is not the place where output order is “required,” and printing a map is not intended to be a report. A good working habit: for output, take map.entries, sort that as a list of records (by key or by value), and print that. This solves both the order problem and the “why is the output slightly different every time?” problem.
Mistake #3: doing too much logic directly inside mapValues { ... }.
mapValues is convenient, but if inside the lambda you have half a screen of code with loops, checks, and formatting, reading turns into a quest. In such cases the code becomes clearer if you move the complex value computation into a separate function (for example, fun groupSum(group: List<Pair<String, Int>>): Int) and leave just one short line in mapValues.
Mistake #4: sorting the result and then printing the original map.
A funny situation happens: you carefully did val sorted = map.entries.sortedByDescending{...}, and then somewhere below you accidentally wrote println(map). As a result, nothing is sorted in the console, and you start suspecting Kotlin of a conspiracy—while the conspiracy was on the side of a single line. A good habit: for a report, print only what you actually prepared for the report (usually that’s sorted or an already built string report).
Mistake #5: hoping it’ll be “good enough” without key normalization.
If keys come from user input or from “dirty” strings, then "Food", " food ", and "FOOD" become three different keys, and your “top categories” will look as if you ate in three different universes. Normalization (trim().lowercase()) should happen before grouping and before counting—otherwise you’ll nicely sort and print… incorrect statistics.
GO TO FULL VERSION