Start learning free

LESSON 191 OF 671 · PROJECTS: EVERYDAY PROGRAMS

Shopping Cart V6 in Java: Group by Category with a HashMap

Practice Read the full explanation

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

You start with:

String[] items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
int[] prices = {2, 3, 25, 1, 40};
String[] categories = {"Food", "Food", "Clothes", "Food", "Clothes"};

Build:

Clothes: $65
Food: $6

Rules:

  • Build a HashMap 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 System.out.println(result).

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

Copy the keys into a list and call Collections.sort on it, then loop over the sorted list.

String[] items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
int[] prices = {2, 3, 25, 1, 40};
String[] categories = {"Food", "Food", "Clothes", "Food", "Clothes"};

HashMap<String, Integer> totals = new HashMap<>();
for (int i = 0; i < items.length; i++) {
    String cat = categories[i];
    totals.put(cat, totals.getOrDefault(cat, 0) + prices[i]);
}
List<String> lines = new ArrayList<>();
List<String> keys = new ArrayList<>(totals.keySet());
Collections.sort(keys);
for (String cat : keys) {
    lines.add(cat + ": $" + totals.get(cat));
}
String result = String.join("\n", lines);
System.out.println(result);

STEP 1 OF 11
    Ctrl + Enter to check

    JAVA · PROJECTS: EVERYDAY PROGRAMS

    Shopping Cart V6 in Java, explained

    Problem overview

    This version summarises a cart by category. Three parallel arrays describe the items: items (names), prices and categories. Position i in each array belongs to the same item. The program adds up the prices per category and prints one line per category, sorted alphabetically by category name.

    For the starter data, Apple (2), Bread (3) and Banana (1) are Food, and Shirt (25) and Pants (40) are Clothes. The output is:

    Clothes: $65
    Food: $6

    Clothes comes first even though the first item in the cart is Food: the order of the lines follows the category names, not the order of the items.

    Approach: accumulate in a map, then sort the keys

    The number of categories is not known in advance, and the items of one category are scattered through the arrays. A HashMap<String, Integer> named totals solves the first part: each category is a key, and its value is the sum of the prices seen so far. For each item the program adds the price to its category's total.

    The first item of a category finds no entry yet. getOrDefault(cat, 0) makes a missing category count as 0, so the same line works for the first item and for every later one.

    The second part is the order. A HashMap gives no order you can rely on, and it cannot be sorted. So the program copies the keys into a list, sorts the list, and builds the output rows by walking the sorted keys and reading each total from the map.

    Step by step

    1. Create totals, an empty HashMap<String, Integer>. One key per category, one running total per key.
    2. Loop over the positions from 0 while i < items.length. The index is needed because prices[i] and categories[i] are linked by position.
    3. Read the category of the current item into cat.
    4. Update the total. totals.put(cat, totals.getOrDefault(cat, 0) + prices[i]) stores the old total, or 0, plus this price, replacing the old entry.
    5. After the loop, create lines, an empty ArrayList of strings for the output rows.
    6. Copy the keys into keys. totals.keySet() gives the categories, and new ArrayList<>(...) copies them into a list that can be sorted.
    7. Sort keys with Collections.sort, which rearranges the list in place.
    8. Loop over the sorted keys with an enhanced for, so cat takes each category once, in alphabetical order.
    9. Add a row for each category: the name, a colon and space, a dollar sign and the total read from the map.
    10. Join the rows with newlines into result, and print it.

    The solution in Java

    String[] items = {"Apple", "Bread", "Shirt", "Banana", "Pants"};
    int[] prices = {2, 3, 25, 1, 40};
    String[] categories = {"Food", "Food", "Clothes", "Food", "Clothes"};
    
    HashMap<String, Integer> totals = new HashMap<>();
    for (int i = 0; i < items.length; i++) {
        String cat = categories[i];
        totals.put(cat, totals.getOrDefault(cat, 0) + prices[i]);
    }
    List<String> lines = new ArrayList<>();
    List<String> keys = new ArrayList<>(totals.keySet());
    Collections.sort(keys);
    for (String cat : keys) {
        lines.add(cat + ": $" + totals.get(cat));
    }
    String result = String.join("\n", lines);
    System.out.println(result);
    

    The Java details worth a closer look:

    • Two loops, one name. The variable cat is declared inside the first loop's body and again as the loop variable of the second loop. That is legal because the first cat is out of scope once the first loop ends.
    • Boxing. The map's values are Integer objects. getOrDefault(cat, 0) + prices[i] unboxes the old value, adds an int and boxes the result again on put. Java does this automatically.
    • keySet() is a view. It is not a list, and it has no sort. Passing it to the ArrayList constructor copies its elements into a real list, so sorting the list leaves the map untouched.
    • How strings sort. Collections.sort on strings uses their natural order, which compares characters by their code. All uppercase letters come before all lowercase letters, so a category named food would sort after Zoo. The lesson's categories all start with a capital letter, so this does not show up there.
    • totals.get(cat) returns an Integer. It cannot be null here, because every key in keys came from the map.
    • Imports. HashMap, List, ArrayList and Collections are all in java.util, so a standalone file needs import java.util.*;.

    Complexity

    Let n be the number of items and k the number of distinct categories.

    Time: O(n + k log k). The first loop does one map update per item, each constant time on average. Sorting the k keys takes O(k log k) comparisons, and building the rows is O(k).

    Space: O(k). The map, the key list and the rows each hold one entry per category.

    Edge cases and common mistakes

    • One category only. Apple (2) and Bread (3), both Food, give the single line Food: $5.
    • No items. With empty arrays the map is empty, lines is empty, and String.join returns an empty string, so the program prints an empty line.
    • Case in category names. Food and food are different keys, because strings are compared exactly. With categories food, Zoo and Food and prices 1, 2 and 3, the output is Food: $3, Zoo: $2 and food: $1, in that order.
    • Using put with only the new price. totals.put(cat, prices[i]) overwrites the sum, so each category would keep only its last price.
    • Using get instead of getOrDefault for the running total. The first item of a category gets null, and the addition throws a NullPointerException.
    • Relying on the map's order. Printing straight from the map can give a different order from the sorted one, and the order of a HashMap is not something a program should depend on.

    Testing

    • The starter arrays give Clothes: $65 then Food: $6.
    • Apple (2) and Bread (3), both Food, give Food: $5.
    • Items a, b, c with prices 1, 2, 3 and categories food, Zoo, Food give Food: $3, Zoo: $2, food: $1.
    • Empty arrays print one empty line.
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free