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
HashMaptotalsthat 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 (soClothescomes beforeFood). - Join the lines with a newline
"\n"into one stringresult, then print it withSystem.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);
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
