Start learning free

LESSON 194 OF 291 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Kotlin: Group by Category with a Map

Practice Read the full explanation

Use a mutable map to accumulate totals per category while looping over parallel arrays, then list the categories sorted by name.

You start with:

        val items = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
        val prices = intArrayOf(2, 3, 25, 1, 40)
        val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")

Build:

Clothes: $65
Food: $6

Rules:

  • Build a mutable map totals that maps each category to the sum of the prices of its items.
  • Loop with an index. For each item, add its price to the total of categories[i]; a category you have not seen yet counts as 0.
  • Make one line per category, in the format "Category: $total", sorted alphabetically by category name (so Clothes comes before Food).
  • Join the lines with a newline "\n" into one string result, then print it with println(result).

Use totals.getOrDefault(cat, 0) + prices[i] to accumulate without checking for missing keys.

Use totals.keys.sorted() to get the keys in alphabetical order.

        val items = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
        val prices = intArrayOf(2, 3, 25, 1, 40)
        val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")

        val totals = mutableMapOf<String, Int>()
        for (i in items.indices) {
            val cat = categories[i]
            totals[cat] = totals.getOrDefault(cat, 0) + prices[i]
        }
        val lines = mutableListOf<String>()
        val keys = totals.keys.sorted()
        for (cat in keys) {
            lines.add(cat + ": $" + totals[cat])
        }
        val result = lines.joinToString("\n")
        println(result)

STEP 1 OF 10
    Ctrl + Enter to check

    KOTLIN · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Kotlin, explained

    Problem overview

    The cart now has categories. Three parallel arrays describe five products: items (names), prices and categories. The program must add up the prices per category and print one line per category, with the categories sorted alphabetically.

    The starting data has apples, bread and bananas in Food, and a shirt and pants in Clothes. The output is:

    Clothes: $65
    Food: $6

    Clothes cost 25 + 40 = 65 and food costs 2 + 3 + 1 = 6. The item names are never printed: only the categories matter in the report.

    Approach: accumulate in a map, then sort the keys

    The categories aren't known in advance, and the same category appears in several places in the arrays. A map from category to running total is the natural fit: each category is a key, and its value grows as items of that category go by. A first sighting of a category has no entry yet, so the total so far counts as 0.

    The program works in two phases. First, one loop over the items fills the map. Second, a loop over the sorted keys builds the output lines. The sorting is a separate step because a map doesn't promise the order you want. The mutableMapOf function in Kotlin does produce a map that remembers the order in which keys were first added, which here would put Food ahead of Clothes, so the alphabetical order has to be asked for explicitly.

    This is the same shape as counting words or tallying votes: group by a key, combine the values that share it. The pattern is worth remembering because it turns a problem that looks like it needs nested loops into a single pass.

    Step by step

    1. Create totals. mutableMapOf<String, Int>() is an empty map from text to integer.
    2. Loop over the positions with items.indices. The same i addresses the same product in all three arrays.
    3. Read the category. Inside the loop, cat is categories[i].
    4. Update the category's total. Set totals[cat] to its current value plus prices[i]. getOrDefault(cat, 0) supplies the current value, or 0 the first time.
    5. Create lines. After the loop, an empty mutableListOf<String>() will hold the output lines.
    6. Sort the keys. totals.keys.sorted() returns the category names as a new, sorted list.
    7. Loop over the sorted keys. The variable cat takes each category once, in alphabetical order.
    8. Add one line per category. It is the category, ": $" and its total.
    9. Join the lines into result with newlines between them.
    10. Print result.

    The solution in Kotlin

            val items = arrayOf("Apple", "Bread", "Shirt", "Banana", "Pants")
            val prices = intArrayOf(2, 3, 25, 1, 40)
            val categories = arrayOf("Food", "Food", "Clothes", "Food", "Clothes")
    
            val totals = mutableMapOf<String, Int>()
            for (i in items.indices) {
                val cat = categories[i]
                totals[cat] = totals.getOrDefault(cat, 0) + prices[i]
            }
            val lines = mutableListOf<String>()
            val keys = totals.keys.sorted()
            for (cat in keys) {
                lines.add(cat + ": $" + totals[cat])
            }
            val result = lines.joinToString("\n")
            println(result)
    

    Kotlin details worth a closer look:

    • Assigning with brackets. totals[cat] = value calls the map's set operator: it adds the key when it is new and replaces the value when it exists. Reading the old value first with getOrDefault is what makes it an accumulation rather than an overwrite.
    • Insertion order. With the starting data, printing totals directly gives {Food=6, Clothes=65}: the keys sit in the order they were first seen. Looping over totals.keys without sorting would therefore print Food first and fail the alphabetical rule.
    • sorted() makes a new list. It sorts the strings in their natural order, which for text means character by character, with uppercase letters before lowercase. The map itself is untouched.
    • A nullable inside the text. totals[cat] is an Int?, but the left side of the + is a String, so it is converted to text anyway. Here every key comes from the map's own key set, so the value is never null.
    • Iterating keys, not entries. Looping over the sorted keys and looking each total up is simple and clear; it costs one lookup per category.

    Complexity

    Only the sorting depends on the number of categories in a way that is more than linear.

    With n items and k distinct categories, the first loop takes O(n) time, because each map update is constant time on average. Sorting the keys takes O(k log k) and building the lines takes O(k). The map and the lists use O(k) extra space.

    Edge cases and common mistakes

    • Overwriting instead of accumulating. Writing totals[cat] = prices[i] keeps only the last price of each category.
    • Skipping the sort. The map's own order is the order of first appearance, not alphabetical.
    • Mixing up the arrays. The category comes from categories[i], not from items[i].
    • No items. With empty arrays, the map is empty, so result is an empty string and println prints an empty line.

    Testing

    Try two items in two categories: Pen at 4 in Office and Mug at 9 in Home. The map holds {Office=4, Home=9}, and the program prints:

    Home: $9
    Office: $4

    The order of the output follows the sorted names, not the order of the products.

    Keep going with Kotlin1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free