CodeGym /Courses /Kotlin SELF /Groupings in reports: list by key and counter by key

Groupings in reports: list by key and counter by key

Kotlin SELF
Level 24, Lesson 4
Available

1. Introduction

When we’re building a learning project, it’s very easy to get stuck on commands like “add record / show list / delete record” and be happy that it at least doesn’t crash. But the real “useful magic” begins when you can answer the user’s questions: “what’s going on with my data?”. Groupings are like taking a box of Lego pieces and sorting them into containers: red ones separately, blue ones separately, and let the round ones live their own life altogether.

In our practical console project (a conditional expense tracker), the data lives in a collection. That means the reports must also be “about collections”: without manual nested loops spanning three screens and without state that’s hard to debug later. Today we’ll neatly connect the day’s techniques to the project logic: we’ll learn once how to make a “list by key” and a “counter by key”, and after that you’ll start seeing these two result shapes in almost any task.

2. Mini data model: an expense record

To display reports, we need some data. Since classes and data class will come later, for now we’ll use a simple structure based on Triple. We’ll agree that one expense record is:

  • category (String)
  • amount (Int)
  • note (String)

Let’s immediately make a small utility so the code in examples is readable. Note: this is not a new type—just a function that creates a Triple.

fun expense(category: String, amount: Int, note: String): Triple<String, Int, String> {
    return Triple(category, amount, note)
}

Now we can assemble test data:

fun main() {
    val expenses = listOf(
        expense("food", 120, "groceries"),
        expense("food", 80, "coffee"),
        expense("taxi", 250, "airport"),
        expense("books", 500, "kotlin")
    )

    println(expenses.size) // 4
}

The main idea: we have a flat list of records. But reports almost always want to see structure: either “sections” (groups) or a “summary” (frequencies).

3. Two result shapes: list and counter by key

Here’s an important point: you don’t need to memorize a million functions. You only need to remember two “answer shapes” that business logic loves. They differ literally by what’s stored in the map value.

Imagine the key is “expense category”.

Then we have two classic results:

What we want What the result looks like How we usually do it
“Show all expenses by category”
Map<String, List<Triple<...>>>
groupBy { category }
“How many expenses are in each category?”
Map<String, Int>
groupingBy { category }.eachCount()

groupBy returns a map where the key is the lambda result and the value is the list of elements in that group.
eachCount() returns a map where the value is simply the number of elements per key.

To keep your brain from overheating, hold onto a simple analogy: groupBy is “folders with files”, and eachCount is “how many files are in each folder”.

A small diagram of how to think about it:

flowchart TD
    A["List⟨ExpenseRecord⟩ (flat list)"] --> B["groupBy { category }"]
    B --> C["Map⟨Category, List⟨ExpenseRecord⟩⟩ (details)"]

    A --> D["groupingBy { category }.eachCount()"]
    D --> E["Map⟨Category, Int⟩ (summary)"]

4. Practice: reports by category

List by category via groupBy

Often, the user wants not only “how many”, but also “what exactly”. For example: “Show what I had in the "food" category.” For that we need grouping with details—groupBy.

Let’s group by category. In our expense record, the category is stored in first.

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("food", 80, "coffee"),
        Triple("taxi", 250, "airport")
    )

    val byCategory: Map<String, List<Triple<String, Int, String>>> =
        expenses.groupBy { it.first }

    println(byCategory.keys) // [food, taxi]
}

Here it’s important to get used to the result type: Map<String, List<...>>. That’s normal because “one category can have many records”—and that’s exactly what a list is.

Now let’s read the groups nicely. We don’t want to print the map “as is” (it doesn’t have to have a convenient order); we want clear output: the category, and under it—the lines.

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("food", 80, "coffee"),
        Triple("taxi", 250, "airport")
    )

    val byCategory = expenses.groupBy { it.first }

    for ((category, items) in byCategory) {
        println("== $category ==")            // == food == (order may differ)
        println("items: ${items.size}")       // items: 2
    }
}

Even such a “semi-report” is already useful: you can see that inside each group there’s an ordinary list, and you can do everything familiar with it—size, sortedBy, for, and so on.

Counter by category via groupingBy().eachCount()

Sometimes you don’t need details. For example, the user asks: “Which categories do I have the most records in overall?” Here you don’t need each category’s list—you only need the numbers.

And this is where groupingBy { ... }.eachCount() is just perfect: it immediately builds a “frequency map” Map<K, Int>.

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("food", 80, "coffee"),
        Triple("taxi", 250, "airport")
    )

    val counts: Map<String, Int> =
        expenses.groupingBy { it.first }.eachCount()

    println(counts) // {food=2, taxi=1}
}

Now we can sort by descending count and make a “top categories” list. We remember the pattern: take entries, sort, print.

fun main() {
    val counts = mapOf("food" to 2, "taxi" to 1, "books" to 5)

    val sorted = counts.entries.sortedByDescending { it.value }
    for ((category, count) in sorted) {
        println("$category -> $count")
        // books -> 5
        // food -> 2
        // taxi -> 1
    }
}

Notice how much shorter the code becomes when you pick the right result shape. If you need numbers—use Map<K, Int>. If you need details—use Map<K, List<T>>.

Two counting approaches: from groups and directly

A very typical project situation: on the same data, you want two different reports.

Let’s imagine we want:

  • “List by categories” (details)
  • “Number of records by categories” (summary)

And here you can feel the difference between two approaches:

  1. You can do groupBy and then turn groups into sizes via mapValues { ... }.
  2. You can immediately do groupingBy().eachCount().

mapValues transforms the map values while keeping the keys—useful when you already have groups and want to post-process them.

Let’s show both options side by side—not as “which is better forever”, but as “which is more appropriate in a specific situation”.

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("food", 80, "coffee"),
        Triple("taxi", 250, "airport")
    )

    val groups = expenses.groupBy { it.first }
    val countsFromGroups = groups.mapValues { (_, items) -> items.size }

    val countsDirect = expenses.groupingBy { it.first }.eachCount()

    println(countsFromGroups) // {food=2, taxi=1}
    println(countsDirect)     // {food=2, taxi=1}
}

In real life you choose like this: if the report truly needs both details and numbers, then start with groupBy, and from those groups do whatever you want (for example, size, sorting inside a group, printing). If the report needs only numbers, then eachCount() saves you from storing lists.

Normalizing the category key

Here’s the moment where half of beginners’ reports break. Grouping works honestly: the key is whatever you returned from the lambda. If you returned "Taxi" and " taxi ", Kotlin treats them as different strings, and it will create two different groups or two different entries in the counter.

That’s why in a project the key almost always needs normalization: trim whitespace and convert to a single case. Let’s immediately extract this into a function so we don’t write the same thing in five places.

fun normalizeCategory(raw: String): String {
    return raw.trim().lowercase()
}

Now use it in grouping:

fun main() {
    val expenses = listOf(
        Triple(" Taxi ", 250, "airport"),
        Triple("taxi", 300, "home"),
        Triple("TAXI", 150, "discount ride")
    )

    val counts = expenses.groupingBy { normalizeCategory(it.first) }.eachCount()
    println(counts) // {taxi=3}
}

This looks like a small detail, but it feels like fastening a seat belt: you can go without it... right up until the first unpleasant surprise.

5. Formatting and CLI integration

Formatting reports and StringBuilder

Once the report is “computed”, the next grown-up question appears: “how do we show this nicely?”. Printing a Map directly is tempting, but the user is not obligated to like the {taxi=3, food=2} format as much as Kotlin does.

Discipline helps here: compute data separately, build text separately.

Let’s make a function that formats a “list by category” report, and print categories in alphabetical order (that’s usually clearer to a human).

import kotlin.text.StringBuilder

fun formatExpensesByCategory(groups: Map<String, List<Triple<String, Int, String>>>): String {
    val sb = StringBuilder()

    val sorted = groups.entries.sortedBy { it.key }
    for ((category, items) in sorted) {
        sb.appendLine("== $category (${items.size}) ==")
        for ((_, amount, note) in items) {
            sb.appendLine("- $amount : $note")
        }
    }

    return sb.toString()
}

Let’s test it on a small example:

fun main() {
    val expenses = listOf(
        Triple("food", 120, "groceries"),
        Triple("taxi", 250, "airport"),
        Triple("food", 80, "coffee")
    )

    val groups = expenses.groupBy { it.first }
    val report = formatExpensesByCategory(groups)

    println(report)
    // == food (2) ==
    // - 120 : groceries
    // - 80 : coffee
    // == taxi (1) ==
    // - 250 : airport
}

Notice the nice effect: the main main stays “clean” and short. And formatting logic lives in a separate function—much easier to change without worrying about breaking input and commands.

Now let’s format the frequency map. Here you usually want to sort by descending frequency and maybe show top-N. We already know take(n) from previous days, so we’ll use it without shame or guilt.

import kotlin.text.StringBuilder

fun formatCategoryCounts(counts: Map<String, Int>, topN: Int): String {
    val sb = StringBuilder()

    val top = counts.entries
        .sortedByDescending { it.value }
        .take(topN)

    for ((category, count) in top) {
        sb.appendLine("$category -> $count")
    }

    return sb.toString()
}

Example:

fun main() {
    val counts = mapOf("food" to 10, "taxi" to 3, "books" to 7)

    val report = formatCategoryCounts(counts, topN = 2)
    println(report)
    // food -> 10
    // books -> 7
}

It’s important to understand that we’re not sorting “the map itself”, but the list of entries. That’s the clearest path: Map is about key→value mapping, and we define the “output order” ourselves, separately.

Hooking reports into the CLI

Now we’ll integrate this with our console application. We’re not writing the whole project (otherwise this lecture would turn into a 48-season series), but we’ll show how to neatly connect two reports to the already familiar command logic.

Suppose we have a list of expenses MutableList<Triple<String, Int, String>> and a command-reading loop. We’ll add two commands:

  • report byCategory — details by categories
  • report counts — how many records are in categories (top-N, e.g., top-5)

Handler skeleton:

fun handleReportCommand(expenses: List<Triple<String, Int, String>>, args: List<String>) {
    val mode = args.getOrNull(0) ?: ""

    when (mode) {
        "byCategory" -> {
            val groups = expenses.groupBy { normalizeCategory(it.first) }
            println(formatExpensesByCategory(groups))
        }
        "counts" -> {
            val counts = expenses.groupingBy { normalizeCategory(it.first) }.eachCount()
            println(formatCategoryCounts(counts, topN = 5))
        }
        else -> {
            println("Unknown report mode: $mode") // Unknown report mode: ...
        }
    }
}

And an example of “how it might be called” from the main loop (simplified). Note: we assume you already have parsing a line into tokens (split, trim) from previous lectures about commands.

fun main() {
    val expenses = mutableListOf(
        Triple("Food", 120, "groceries"),
        Triple(" taxi ", 250, "airport"),
        Triple("food", 80, "coffee")
    )

    val cmd = "report counts"
    val parts = cmd.trim().split(" ").filter { it.isNotBlank() }

    if (parts.firstOrNull() == "report") {
        handleReportCommand(expenses, parts.drop(1))
    }
}

The point here is not that you memorize the “perfect command format”, but that you see the architectural idea: the command chooses the report, and the report chooses the result shape.

If you need details—groupBy and then format the groups. If you need a summary—eachCount and then format the frequency map.

6. Common mistakes

Mistake #1: choose groupBy when you only need numbers, and then be surprised that everything became “heavy”.
Beginners often automatically reach for groupBy because it feels “clearer”. But a Map<K, List<T>> stores entire lists of elements, and if you only need “how many”, that’s extra work and extra memory. In a project it looks like this: you build groups, then immediately take .size and throw away the details. In those cases, it’s better to use groupingBy { ... }.eachCount() right away and get a Map<K, Int>.

Mistake #2: don’t normalize the key and end up with “drifted” categories.
If the user types categories manually, you’re almost guaranteed to get "Food", " food", "FOOD" as different keys. Grouping works correctly, but the report looks as if the user has three different categories. The fix is to perform normalization (trim().lowercase()) inside the key selector, not “somewhere later” when it’s already too late.

Mistake #3: read groups via groups[key]!! and crash on a missing key.
When you read a value from a Map, Kotlin fairly returns V? because the key may be absent. If in a report you do groups["food"]!!, but the "food" category doesn’t exist (or it became " Food " and wasn’t normalized), you’ll get a NullPointerException right where the user expected “just a report”. In reporting logic it’s better to iterate over entries or use safe options like groups[key].orEmpty().

Mistake #4: print a Map directly and expect a “nice” order.
It’s tempting to do println(counts) and consider the task done. But the order in a map’s output is not part of the “readable report” contract. The user usually wants either sorting by key (alphabetical) or sorting by value (descending frequency). So the proper path is: counts.entries.sortedBy... and only then print.

Mistake #5: mix computation and formatting into one giant chain.
Chaining collection operations is great as long as you can read it. When you cram normalization, grouping, sorting, take, string building, and printing into one line, you end up with “puzzle code” that’s hard to change. It’s much more stable to split into 2–3 intermediate vals: counts, sorted, reportText. That way you help yourself, and debugging becomes easier.

1
Task
Kotlin SELF, level 24, lesson 4
Locked
Expense categories
Expense categories
1
Task
Kotlin SELF, level 24, lesson 4
Locked
Frequencies from a string
Frequencies from a string
1
Task
Kotlin SELF, level 24, lesson 4
Locked
Category normalization
Category normalization
1
Task
Kotlin SELF, level 24, lesson 4
Locked
Well-formatted report
Well-formatted report
1
Survey/quiz
Groupings and frequencies, level 24, lesson 4
Unavailable
Groupings and frequencies
Groupings and frequencies
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION