HashMap for frequencies
Quick answer
A hash map associates unique keys with values. It is useful for counting categories or retrieving information by an identifier instead of a numeric position.
Entry updates
Import std::collections::HashMap. insert replaces the value for an equal existing key; get borrows a stored value. entry(key).or_insert(0) creates a zero only if the key is absent and returns a mutable reference. Equal keys must hash consistently; iteration order is unspecified.
use std::collections::HashMap;fn main() { let mut counts = HashMap::new(); for tag in ["red", "blue", "red"] { *counts.entry(tag).or_insert(0) += 1; } println!("red: {}", counts["red"]);}Expected stdout (not executed):
red: 2The same entry receives two increments.
use std::collections::HashMap;fn main() { let mut stock = HashMap::from([("pen", 3)]); println!("old: {:?}", stock.insert("pen", 5)); println!("new: {:?}", stock.get("pen"));}Expected stdout (not executed):
old: Some(3)new: Some(5)Insert reports the previous value.
Common mistake
Never rely on hash map iteration order in expected output; sort keys first or use BTreeMap.
Try it yourself
Count the words in ["tea", "tea", "milk"] and print the counts by named keys.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
HashMap for frequencies — practice quiz
Choose one answer per question, then review the explanation.
A HashMap stores red → 2. Inserting red → 7 changes the value to what?
What does `entry(key).or_insert(0)` yield for an existing key?
How should a frequency map produce reproducible alphabetical output?