Look up by meaning.
Count and update keyed values without duplicate lookups.
01 Understand the contract
HashMap<K, V> associates keys with values. insert takes ownership of owned keys and values; get borrows and returns Option<&V>. The entry API combines lookup with conditional insertion, which is useful for counters and caches. Iteration order is not a stable contract. Sort entries or use BTreeMap when deterministic key order is part of your output. Expected lookup is constant time under normal hashing assumptions, but hashing the key still costs work proportional to its representation.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for word in "build test build".split_whitespace() {
*counts.entry(word).or_insert(0_u32) += 1;
}
println!("build={}", counts["build"]);
println!("missing={:?}", counts.get("ship"));
}build=2 missing=None
- 1
entry gives access to an existing or inserted counter.
- 2
The keys borrow the static text in this example.
- 3
get is appropriate when the key may not exist.
cargo run -p lesson_hash_maps03 Mind the boundary
04 Your next build
Count character frequencies and assert both a repeated and a missing character.
Reveal one possible solution +
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for ch in "banana".chars() {
*counts.entry(ch).or_insert(0) += 1;
}
assert_eq!(counts.get(&'a'), Some(&3));
assert_eq!(counts.get(&'x'), None);
}05 Check your reasoning
Does HashMap guarantee iteration in insertion order?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.