Count and group values with maps
Count and group values with maps
Missing integer entries read as zero, so counts[item]++ counts the first occurrence and increments subsequent occurrences. Allocate the map before writing. A map of slices can group multiple values under one key.
package main
import "fmt"
func main() { counts := make(map[string]int) for _, item := range []string{"tea", "rice", "tea", "tea"} { counts[item]++ } fmt.Println(counts["tea"], counts["rice"], counts["bread"])}Each occurrence adds one to the current count. Bread was never inserted, but reading its count still returns zero. Use comma-ok if a stored zero and absence have different meanings.
Expected output:
3 1 0Group numbers by remainder
package main
import "fmt"
func main() { groups := make(map[int][]int) for _, n := range []int{1, 2, 3, 4, 5} { k := n % 2 groups[k] = append(groups[k], n) } fmt.Println(groups[0]) fmt.Println(groups[1])}A missing slice value is nil, and append accepts nil. Store the returned slice back in the map because append may change its length and backing array. Each group preserves the input order; map key order remains unspecified.
Expected output:
[2 4][1 3 5]Try it locally
Count occurrences in []int{2,1,2,3,2,1}. Print counts for 1, 2, 3 and 4 in that order.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 07: Count and group values with maps
Check the lesson objective before moving on.
Why does counts[k]++ work for a new key in a non-nil integer map?
How do you append v to a slice stored under k?