Drill

ProblemsJava › data

How many of each

easydataHash mapsArraysJava

A survey tallies how often each answer was given.

groupSizes(values: list<string>) → 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> groupSizes(List<String> values) {
    
}

Worked examples

CallResult
groupSizes(Main.<String>ls("a", "b", "a"))Main.<String, Integer>mp("a", 2, "b", 1)
groupSizes(Main.<String>ls("x"))Main.<String, Integer>mp("x", 1)
groupSizes(Main.<String>ls("p", "p", "p"))Main.<String, Integer>mp("p", 3)
groupSizes(Main.<String>ls("a", "b", "c"))Main.<String, Integer>mp("a", 1, "b", 1, "c", 1)

Hint

Add one to the map entry for each value you meet.

Reference solution in Java
Map<String, Integer> groupSizes(List<String> values) {
    Map<String, Integer> result = new LinkedHashMap<>();
    for (String v : values) result.merge(v, 1, Integer::sum);
    return result;
}

The same problem in another language

More data problems in Java