Drill

ProblemsJava › data

Totals per category

mediumdataHash mapsArraysJava

A ledger groups every sale under its category so each bucket shows a single sum.

sumPerCategory(sales: list<Sale>) → 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.

Solve it in Python →

Where you start

Map<String, Integer> sumPerCategory(List<Sale> sales) {
    
}

Worked examples

CallResult
sumPerCategory(Main.<Sale>ls(new Sale("food", 10), new Sale("food", 15)))Main.<String, Integer>mp("food", 25)
sumPerCategory(Main.<Sale>ls(new Sale("a", 3), new Sale("b", 4), new Sale("a", 5)))Main.<String, Integer>mp("a", 8, "b", 4)
sumPerCategory(Main.<Sale>ls(new Sale("x", 1)))Main.<String, Integer>mp("x", 1)
sumPerCategory(Main.<Sale>ls(new Sale("p", 0), new Sale("q", -2)))Main.<String, Integer>mp("p", 0, "q", -2)

Hint

Aggregate into a map keyed by category, adding each amount as you go.

Reference solution in Java
Map<String, Integer> sumPerCategory(List<Sale> sales) {
    Map<String, Integer> result = new LinkedHashMap<>();
    for (Sale s : sales) result.merge(s.category, s.amount, Integer::sum);
    return result;
}

The same problem in another language

More data problems in Java