Start learning free

LESSON 167 OF 414 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 - Group by Category in Scala

Practice

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 = Array("Apple", "Bread", "Shirt", "Banana", "Pants")
        val prices = Array(2, 3, 25, 1, 40)
        val categories = Array("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.getOrElse(cat, 0) + prices(i) to accumulate without checking for missing keys.

Use totals.keys.toSeq.sorted to get the keys in alphabetical order.

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

        val totals = scala.collection.mutable.Map[String, Int]()
        for (i <- items.indices) {
            val cat = categories(i)
            totals(cat) = totals.getOrElse(cat, 0) + prices(i)
        }
        val lines = scala.collection.mutable.ArrayBuffer[String]()
        val keys = totals.keys.toSeq.sorted
        for (cat <- keys) {
            lines += cat + ": $" + totals(cat)
        }
        val result = lines.mkString("\n")
        println(result)

STEP 1 OF 10
    Ctrl + Enter to check

    Shopping Cart V6 in Scala

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