Average spend per category
A budgeting view shows what a typical transaction looks like in each category.
- Amounts are never negative.
- The average is a whole number, rounded half up: 12.5 becomes 13.
- A category with no entries never appears.
averagePerCategory(entries: list<Entry>) → map<string, int>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
Map<String, Integer> averagePerCategory(List<Entry> entries) {
}
Worked examples
| Call | Result |
|---|---|
averagePerCategory(Main.<Entry>ls(new Entry("food", 10), new Entry("food", 15))) | Main.<String, Integer>mp("food", 13) |
averagePerCategory(Main.<Entry>ls(new Entry("rent", 3000), new Entry("food", 40), new Entry("food", 20))) | Main.<String, Integer>mp("rent", 3000, "food", 30) |
averagePerCategory(Main.<Entry>ls(new Entry("x", 0))) | Main.<String, Integer>mp("x", 0) |
averagePerCategory(Main.<Entry>ls()) | Main.<String, Integer>mp() |
Hint
Collect sums and counts side by side, then divide once at the end. (sum + count / 2) / count rounds half up in integers.
Reference solution in Java
Map<String, Integer> averagePerCategory(List<Entry> entries) {
Map<String, Integer> sums = new LinkedHashMap<>(), counts = new LinkedHashMap<>();
for (Entry e : entries) {
sums.merge(e.category, e.amount, Integer::sum);
counts.merge(e.category, 1, Integer::sum);
}
Map<String, Integer> result = new LinkedHashMap<>();
for (Map.Entry<String, Integer> kv : sums.entrySet()) {
int n = counts.get(kv.getKey());
result.put(kv.getKey(), (kv.getValue() + n / 2) / n);
}
return result;
}