Counting and Grouping
Common map-based patterns.
Counting Things
A very common task is counting how many times each value appears in a collection.
A HashMap from value to count is the natural tool. The key is the item, the value is its tally.
The Counting Pattern
For each item, look up its slot, default it to zero, and add one.
The entry API makes this a single, clear line. This pattern works for any countable item.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for n in [1, 1, 2, 3, 3, 3] {
*counts.entry(n).or_insert(0) += 1;
}
println!("threes: {}", counts[&3]);
}All lessons in this course
- Building a HashMap
- Entry API and Defaults
- Working with HashSet
- Counting and Grouping