Counting with Maps
Counting is one of the most common jobs for a map. How many times does each word appear in a text? How many votes did each name get? The words or names are the keys, and the counts are the values.
package main
import "fmt"
func main() {
votes := []string{
"Bob", "Alice", "Bob",
"Emma", "Bob", "Alice",
}
counts := map[string]int{}
for _, name := range votes {
counts[name]++
}
fmt.Println(counts)
}
Output:
map[Alice:2 Bob:3 Emma:1]
The whole counting step is one line: counts[name]++. It works because of what you learned in the Maps lesson. The first time a name appears, it is not in the map yet, so counts[name] reads as 0. The ++ makes it 1 and stores it under that name. The next time the same name appears, the count goes from 1 to 2, and so on. You never need to check if the key is already there.
Printing in a fixed order
fmt.Println(counts) printed the names in sorted order. But usually you want your own format, one name per line. A range loop gives you that, and you saw in the last lesson that its order changes from run to run. A program whose output changes every time is hard to test and hard to read.
The fix has three steps. Collect the keys into a slice, sort the slice with slices.Sort from The slices Package lesson, and then loop over the sorted slice. Here the map is written as a literal, so you can see the steps on their own:
counts := map[string]int{
"Bob": 3, "Alice": 2, "Emma": 1,
}
names := []string{}
for name := range counts {
names = append(names, name)
}
slices.Sort(names)
for _, name := range names {
fmt.Println(name, counts[name])
}
Output:
Alice 2
Bob 3
Emma 1
The first loop visits the keys in any order, but that does not matter, because the slice is sorted right after. The second loop goes over the slice, and a slice always keeps its order. Use this pattern whenever you print a map line by line.
Grouping values
A map's value can also be a slice. Then each key holds a group of values. Here each word goes into a group by its length:
words := []string{"cat", "bird", "dog", "fish", "ox"}
groups := map[int][]string{}
for _, w := range words {
groups[len(w)] = append(groups[len(w)], w)
}
fmt.Println(groups)
fmt.Println(groups[5], len(groups[5]))
Output:
map[2:[ox] 3:[cat dog] 4:[bird fish]]
[] 0
The same zero-value idea is at work. For a new length, groups[len(w)] reads as an empty slice, and append works on it without any special case. Asking for a key that is not there, like 5, gives an empty slice with length 0.
Has it been seen before?
A map with bool values can remember which things you have already met. A missing key reads as false. This loop finds the first word that appears twice:
words := []string{"red", "blue", "green", "blue", "red"}
seen := map[string]bool{}
for _, w := range words {
if seen[w] {
fmt.Println("first repeat:", w)
break
}
seen[w] = true
}
Output:
first repeat: blue
Checking a map is fast, even with many keys, so this is much quicker than comparing every word with every other word. You will meet this idea often in coding interview problems.
In the exercise, count the words from the input and print each word with its count in sorted order.