How many of each
A survey tallies how often each answer was given.
- Count how many times each distinct string appears.
- Every distinct value that appears earns an entry in the result.
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.
Where you start
Map<String, Integer> groupSizes(List<String> values) {
}
Worked examples
| Call | Result |
|---|---|
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;
}