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
- Create
totals, an emptyHashMap<String, Integer>. One key per category, one running total per key. - Loop over the positions from 0 while
i < items.length. The index is needed becauseprices[i]andcategories[i]are linked by position. - Read the category of the current item into
cat. - 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. - After the loop, create
lines, an emptyArrayListof strings for the output rows. - Copy the keys into
keys.totals.keySet()gives the categories, andnew ArrayList<>(...)copies them into a list that can be sorted. - Sort
keyswithCollections.sort, which rearranges the list in place. - Loop over the sorted keys with an enhanced
for, socattakes each category once, in alphabetical order. - Add a row for each category: the name, a colon and space, a dollar sign and the total read from the map.
- 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
catis declared inside the first loop's body and again as the loop variable of the second loop. That is legal because the firstcatis out of scope once the first loop ends. - Boxing. The map's values are
Integerobjects.getOrDefault(cat, 0) + prices[i]unboxes the old value, adds anintand boxes the result again onput. Java does this automatically. keySet()is a view. It is not a list, and it has nosort. Passing it to theArrayListconstructor copies its elements into a real list, so sorting the list leaves the map untouched.- How strings sort.
Collections.sorton strings uses their natural order, which compares characters by their code. All uppercase letters come before all lowercase letters, so a category namedfoodwould sort afterZoo. The lesson's categories all start with a capital letter, so this does not show up there. totals.get(cat)returns anInteger. It cannot benullhere, because every key inkeyscame from the map.- Imports.
HashMap,List,ArrayListandCollectionsare all injava.util, so a standalone file needsimport 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,
linesis empty, andString.joinreturns an empty string, so the program prints an empty line. - Case in category names.
Foodandfoodare different keys, because strings are compared exactly. With categoriesfood,ZooandFoodand prices 1, 2 and 3, the output isFood: $3,Zoo: $2andfood: $1, in that order. - Using
putwith only the new price.totals.put(cat, prices[i])overwrites the sum, so each category would keep only its last price. - Using
getinstead ofgetOrDefaultfor the running total. The first item of a category getsnull, and the addition throws aNullPointerException. - 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
HashMapis not something a program should depend on.
Testing
- The starter arrays give
Clothes: $65thenFood: $6. - Apple (2) and Bread (3), both Food, give
Food: $5. - Items a, b, c with prices 1, 2, 3 and categories
food,Zoo,FoodgiveFood: $3,Zoo: $2,food: $1. - Empty arrays print one empty line.
