Rust / Intermediate / Lesson 14
HashMap entry and frequency counts
Build Rust frequency maps with the entry API and stable keys.
On this page
Lesson goals
- Use entry for insertion or update.
- Test missing keys without relying on iteration order.
- Trace occupied and vacant entry updates, key ownership, and borrow scope.
- Design frequency tests with explicit normalization, overflow, absence, and report-order policies.
Define a frequency contract
A frequency table maps each distinct key to a count. Building one is a useful exercise in map ownership, mutation, and boundary behavior. Define whether keys are case-sensitive and whether empty input is valid before writing the loop. A map does not inherently preserve insertion order, so avoid asserting a printed order unless the chosen collection explicitly guarantees it.
Update an entry
The entry API combines lookup and insertion for a key. or_insert supplies an initial value only if the key is absent and returns a mutable reference to the stored value. The example dereferences that reference to increment the count. The map owns the keys and values it stores; decide whether borrowed keys remain valid for the map’s full lifetime or whether owned strings are required.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for word in ["red", "blue", "red"] {
*counts.entry(word).or_insert(0) += 1;
}
println!("{}", counts["red"]);
}
2
The second red entry updates the existing count.
Handle a missing key
A lookup returns an Option because a key may be absent. Handle that outcome rather than unwrapping based on an unverified assumption. The example supplies zero only as a display fallback; its domain must explicitly permit missing keys to mean a zero count. When missing data represents an error, propagate or report that error instead of hiding it behind a fallback.
use std::collections::HashMap;
fn main() {
let counts = HashMap::from([("red", 2)]);
let missing = counts.get("blue").copied().unwrap_or(0);
println!("{missing}");
}
0
The absent key uses the documented zero fallback.
Control the mutable borrow
The mutable reference returned by entry borrows the map. Do not hold it while requesting another incompatible mutable access to the same map. Finish the update before the next operation, or restructure the code into separate scopes. If counts can exceed the integer type’s range, use checked addition and decide how to report overflow before storing the updated value.
Test counts by key
Test empty input, a single key, repeated keys, and a missing lookup. Assert counts by key rather than depending on HashMap iteration order. If normalization is required, test inputs that differ only by the documented normalization rule and keep that transformation at a clear boundary. A small table of expected counts makes ownership changes and later optimizations easier to verify.
Define the keys and counts
A frequency map associates each distinct key with a count. Before choosing a loop, define what constitutes the same key, whether empty input is valid, and whether a missing key means zero or a data error. A case-sensitive table treats "Red" and "red" as different keys; an ASCII-lowercase policy can combine them, but it is not a general Unicode normalization or locale-aware case-folding policy. Tokenization is another separate choice: splitting on whitespace does not automatically remove punctuation. Write these choices as part of the data contract and test them with inputs that distinguish the policies.
A HashMap does not promise a stable iteration order, even when the same small fixture appears in a particular order on one run. Test counts by key, or sort an extracted list when the report requires a deterministic order. BTreeMap provides key-ordered traversal, although its string ordering is not automatically human-language collation. Empty input should normally create an empty map if that is the stated contract; a missing lookup should not be confused with a stored zero unless the application explicitly chooses that interpretation. A map of counts does not itself enforce a maximum input size, a count overflow policy, or a normalization rule.
Entry, mutation, and borrow scope
entry takes a key and returns an Entry representing an occupied or vacant slot. or_insert supplies a default value when vacant and yields a mutable reference to the stored value in either case. In *counts.entry(key).or_insert(0) += 1, dereferencing updates the stored counter. The first observation changes zero to one; subsequent equal keys update the existing counter. or_insert evaluates its argument before the method call even if the entry is occupied, whereas or_insert_with computes its default lazily only when needed. Choose the latter when default construction is expensive or should not happen for an existing entry.
The mutable reference returned from entry borrows the map. Finish its last use before requesting another incompatible mutable access to that map. A later use of the reference can extend the conflict across a second entry or insert; keeping updates in short phases makes the access pattern easier to understand. and_modify can update an occupied value before or_insert supplies a vacant default, but its order and initial value must match the intended count. For a new observation, and_modify(|n| *n += 1).or_insert(1) starts a new key at one rather than zero. Neither approach eliminates arithmetic overflow or resource requirements.
Keys, equality, and stable storage
A map stores its key values. With HashMap<String, u32>, the map owns each inserted String; with HashMap<&str, u32>, it stores references whose source text must remain valid for their uses. String literals can be borrowed for the program lifetime, but a slice of a temporary local String cannot safely escape that owner. An owned key is useful when the map must survive the input buffer, although creating owned keys can allocate. Lookup of a String key can use a compatible borrowed str; callers need not construct a new String solely to query an existing key.
HashMap relies on key equality and hashing being consistent: equal keys must hash equally. Do not mutate a key in a way that changes its equality or hash while it is stored; design immutable key representations and perform normalization before insertion. Deriving Eq and Hash for a suitable local key type is often useful, but the chosen fields must represent the intended identity. Two records with different display labels might share an identifier; decide which field is the key before counting. A syntactically valid key type does not prove the product’s identity policy or safe handling of sensitive text.
Overflow, missing keys, and partial work
Integer counters have finite ranges. With a u8 count already at 255, an ordinary increment is not a domain policy: use checked_add when overflow must be rejected, and write the new value only after the check succeeds. Saturating or wrapping arithmetic is appropriate only when the application explicitly requires it; each loses information about an exact unrepresentable count. If a batch must be all-or-nothing, staging counts separately before committing can protect in-memory state, but external writes require their own transaction or compensation. An error result does not automatically roll back earlier changes.
get returns Option<&V> for a missing or present key. copied can turn Option<&u32> into Option<u32>; unwrap_or(0) is appropriate for a report only when absence is defined as zero. Direct map indexing panics if the key is absent, so use it only when the invariant is established and that behavior is acceptable. Distinguish a stored zero from no entry when the distinction matters. Tests should include empty input, one key, repeated keys, a missing lookup, a maximum count, and a rejected increment that leaves the prior value unchanged. Verify map state as well as an error or return flag.
Build, report, and verify
An ingestion workflow can validate and normalize a token before mutating the map, then update the chosen key with the documented count policy. If empty tokens are disallowed, reject or skip them explicitly rather than depending on accidental behavior of one tokenizer. If the source is untrusted, set limits on the number of distinct keys, token size, and total records; a memory-safe HashMap can still exhaust resources. Consider whether a rejected record leaves previous counts unchanged and whether the operation is a single-record update or an atomic batch.
Separate aggregation tests from report-order tests. For input ["tea", "milk", "tea"], verify tea maps to two and milk to one independently of traversal order. If the report must be alphabetical under Rust’s string ordering, collect keys and sort them or use BTreeMap, then assert the ordered sequence. Test the normalization policy with both equivalent and deliberately distinct tokens, and verify that a missing-key fallback does not insert a new entry. The course baseline is stable Rust 1.85 or newer, edition 2024. Fragments below use synthetic fixtures and are illustrative and unexecuted here; their results are reasoned from the documented APIs, not claimed tool output.
20 worked examples
1. First observation
Problem: Determine the count after inserting one occurrence.
- The key tea is initially vacant, so or_insert stores zero.
- The mutable reference is incremented to one.
let mut m = std::collections::HashMap::new();
*m.entry("tea").or_insert(0_u32) += 1;
Illustrative fragment; not compiled or executed.
Expected result: m["tea"] = 1
Why this result follows: The entry update initializes and increments the same stored value.
2. Existing observation
Problem: Trace the update for an already present key.
- The tea entry already holds one, so the default is not stored.
- The returned mutable reference increments the existing count to two.
let mut m = std::collections::HashMap::from([("tea", 1_u32)]);
*m.entry("tea").or_insert(0) += 1;
Illustrative fragment; not compiled or executed.
Expected result: m["tea"] = 2
Why this result follows: Entry selects the occupied value rather than resetting it.
3. Two keys
Problem: Compute each frequency without relying on iteration order.
- The first a and b each create a count of one.
- The final a updates only its own entry to two.
let mut m = std::collections::HashMap::new();
for key in ["a", "b", "a"] { *m.entry(key).or_insert(0_u32) += 1; }
Illustrative fragment; not compiled or executed.
Expected result: a = 2; b = 1
Why this result follows: A frequency map maintains a separate value per distinct key.
4. Empty lookup
Problem: Determine the missing result in an empty map.
- No key has been inserted into the map.
- get reports absence and does not add an entry.
let m: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
let result = m.get("a");
Illustrative fragment; not compiled or executed.
Expected result: result = None; m.len() = 0
Why this result follows: A checked lookup distinguishes absence without mutating the map.
5. Zero versus absent
Problem: Compare a stored zero with a missing entry.
- Key a exists and points to a stored zero.
- Key b is absent, so its lookup returns None.
let m = std::collections::HashMap::from([("a", 0_u32)]);
let present = m.get("a");
let missing = m.get("b");
Illustrative fragment; not compiled or executed.
Expected result: present = Some(&0); missing = None
Why this result follows: Option preserves the distinction until the caller chooses a policy.
6. Display fallback
Problem: Determine the fallback and whether the map changes.
- The b lookup returns None because only a is present.
- unwrap_or supplies zero to the caller without inserting b.
let m = std::collections::HashMap::from([("a", 2_u32)]);
let shown = m.get("b").copied().unwrap_or(0);
Illustrative fragment; not compiled or executed.
Expected result: shown = 0; m.len() = 1
Why this result follows: A read fallback is not an insertion operation.
7. Modify an occupied entry
Problem: Trace the occupied branch of the update chain.
- The key a exists with count three.
- and_modify increments it to four and or_insert leaves it present.
let mut m = std::collections::HashMap::from([("a", 3_u32)]);
m.entry("a").and_modify(|n| *n += 1).or_insert(1);
Illustrative fragment; not compiled or executed.
Expected result: m["a"] = 4
Why this result follows: The occupied path updates the stored count once.
8. Insert a vacant entry
Problem: Trace the vacant branch of the update chain.
- The key a is absent, so and_modify does not run its closure.
- or_insert inserts one for this first occurrence.
let mut m: std::collections::HashMap<&str, u32> = std::collections::HashMap::new();
m.entry("a").and_modify(|n| *n += 1).or_insert(1);
Illustrative fragment; not compiled or executed.
Expected result: m["a"] = 1
Why this result follows: The vacant default directly represents the first observation.
9. Lazy default
Problem: Determine whether an occupied entry invokes its default closure.
- Key a already has the stored value two.
- or_insert_with does not call the closure for this occupied entry.
let mut m = std::collections::HashMap::from([("a", 2_u32)]);
let mut calls = 0;
m.entry("a").or_insert_with(|| { calls += 1; 9 });
Illustrative fragment; not compiled or executed.
Expected result: calls = 0; m["a"] = 2
Why this result follows: Lazy default construction is skipped when the key exists.
10. Eager default expression
Problem: Determine whether the default expression runs for an occupied entry.
- The or_insert argument is evaluated before the method call.
- The occupied entry keeps two even though calls increases to one.
let mut m = std::collections::HashMap::from([("a", 2_u32)]);
let mut calls = 0;
m.entry("a").or_insert({ calls += 1; 9 });
Illustrative fragment; not compiled or executed.
Expected result: calls = 1; m["a"] = 2
Why this result follows: Eager argument evaluation differs from or_insert_with’s lazy closure.
11. Sequential mutable entries
Problem: Explain why these two updates can occur in sequence.
- The first mutable entry reference is no longer used after its update.
- The second entry borrow begins after that relevant use.
let mut m = std::collections::HashMap::new();
*m.entry("a").or_insert(0_u32) += 1;
*m.entry("b").or_insert(0_u32) += 1;
Illustrative fragment; not compiled or executed.
Expected result: a = 1; b = 1
Why this result follows: Separate access phases avoid overlapping mutable map borrows.
12. Overlapping entries
Problem: Identify why these mutable entry references conflict.
- The final expression uses both mutable references together.
- Creating b requires another mutable borrow while a remains needed.
let mut m = std::collections::HashMap::new();
let a = m.entry("a").or_insert(0_u32);
let b = m.entry("b").or_insert(0_u32);
*a += *b;
Illustrative fragment; not compiled or executed.
Expected result: rejected: overlapping mutable map borrows
Why this result follows: The map cannot be mutably borrowed twice in this pattern.
13. Reject overflow before assignment
Problem: Trace the attempted increment at the u8 maximum.
- The existing count 255 cannot be increased within u8.
- checked_add returns None, so the assignment is skipped.
let mut m = std::collections::HashMap::from([("a", 255_u8)]);
let n = m.get_mut("a").unwrap();
let next = n.checked_add(1);
if let Some(value) = next { *n = value; }
Illustrative fragment; not compiled or executed.
Expected result: next = None; m["a"] = 255
Why this result follows: The old count remains unchanged when the checked update fails.
14. Borrowed string lookup
Problem: Find the owned String key using a string slice.
- The map owns a String key containing oak.
- get accepts a compatible borrowed str and finds the stored count.
let mut m = std::collections::HashMap::<String, u32>::new();
m.insert(String::from("oak"), 2);
let n = m.get("oak");
Illustrative fragment; not compiled or executed.
Expected result: n = Some(&2)
Why this result follows: A lookup need not allocate another owned String key.
15. Case-sensitive keys
Problem: Determine the counts without normalization.
- The two input strings differ in ASCII letter case.
- They remain distinct keys and each appears once.
let words = ["Red", "red"];
let mut m = std::collections::HashMap::new();
for word in words { *m.entry(word).or_insert(0_u32) += 1; }
Illustrative fragment; not compiled or executed.
Expected result: Red = 1; red = 1
Why this result follows: HashMap uses the key’s equality rather than an implicit case policy.
16. ASCII normalization
Problem: Determine the combined count under the specified policy.
- ASCII lowercasing converts Red to red and leaves red unchanged.
- Both normalized keys update the same count.
let words = ["Red", "red"];
let mut m = std::collections::HashMap::new();
for word in words { *m.entry(word.to_ascii_lowercase()).or_insert(0_u32) += 1; }
Illustrative fragment; not compiled or executed.
Expected result: red = 2
Why this result follows: Normalizing before entry defines the equality boundary for this table.
17. Sort for a report
Problem: Determine the stable key sequence after sorting.
- HashMap traversal order is not the report contract.
- Sorting the extracted ASCII keys places apple before pear.
let m = std::collections::HashMap::from([("pear", 2), ("apple", 1)]);
let mut keys: Vec<_> = m.keys().copied().collect();
keys.sort();
Illustrative fragment; not compiled or executed.
Expected result: keys = ["apple", "pear"]
Why this result follows: A separate sorted key list supplies the requested presentation order.
18. Ordered map report
Problem: Determine the key traversal order of this map.
- BTreeMap traverses keys according to their ordering.
- The ASCII key apple precedes pear.
let m = std::collections::BTreeMap::from([("pear", 2), ("apple", 1)]);
let keys: Vec<_> = m.keys().copied().collect();
Illustrative fragment; not compiled or executed.
Expected result: keys = ["apple", "pear"]
Why this result follows: Ordered storage makes this report sequence deterministic.
19. Replace versus increment
Problem: Trace an insert on an existing key.
- The key a already maps to one.
- insert replaces it with seven and returns the prior value.
let mut m = std::collections::HashMap::from([("a", 1_u32)]);
let old = m.insert("a", 7);
Illustrative fragment; not compiled or executed.
Expected result: old = Some(1); m["a"] = 7
Why this result follows: insert replacement is distinct from a frequency increment.
20. Remove an entry
Problem: Determine the removed value and remaining key status.
- remove finds key a with count two.
- It returns that count and removes the association.
let mut m = std::collections::HashMap::from([("a", 2_u32), ("b", 1)]);
let removed = m.remove("a");
Illustrative fragment; not compiled or executed.
Expected result: removed = Some(2); a is absent
Why this result follows: Removal transfers the stored value and makes subsequent lookup absent.
Common errors and fixes
A missing key causes a panic
- Why it happens
- Indexing assumed the key existed.
- How to fix it
- Use get and handle None.
- Prevent it next time
- Test a missing key.
A second mutable borrow is rejected
- Why it happens
- An earlier entry borrow is still used.
- How to fix it
- Finish the first update before borrowing again.
- Prevent it next time
- Keep borrow scopes small.
A test fails due to key order
- Why it happens
- HashMap iteration order was assumed.
- How to fix it
- Check each key or sort a collected result.
- Prevent it next time
- Document any ordering requirement.
20 practice exercises
1. How many times does red occur in the first example?
Show hint
Track the stored red count after each matching word.
Show worked solution
Twice. The first entry starts at zero and increments to one; the later entry increments the stored value to two.
The first red occurrence inserts zero and increments it to one; blue updates a different entry; the final red increments the existing count to two. The answer is two, independent of map traversal order.
Check your solution
- red is inserted and incremented to 1
- The second red makes the count 2
2. Why should a test not compare the map’s unsorted printed order?
Show hint
Separate key/value correctness from display ordering.
Show worked solution
HashMap does not promise a stable iteration order. Assert the values for specific keys or sort an extracted representation.
HashMap does not promise iteration order, so a fixed unsorted formatted string can vary without a count defect. Assert counts for red and blue by key, or sort extracted keys before asserting a report sequence.
Check your solution
- Counts are checked by key
- A report sequence is sorted before comparison
3. Count ["sun", "rain", "sun", "wind", "rain"] and state each frequency without assuming map order.
Show hint
Track each key independently.
Show worked solution
The counts are sun: 2, rain: 2, and wind: 1. Assert each value by key rather than comparing the unsorted map display, since HashMap traversal order is not guaranteed.
Check your solution
- sun and rain each have count 2
- wind has count 1
4. A map starts empty. Describe how entry and or_insert(0) process three occurrences of "x" and give the intermediate counts.
Show hint
The returned reference points to the stored count.
Show worked solution
The first occurrence inserts zero then increments it to 1. The second and third find the occupied entry and increment it to 2 and 3; no later occurrence resets the count.
Check your solution
- Intermediate counts are 1, 2, 3
- Only one x entry exists
5. An update uses and_modify to increment existing counts. Choose the or_insert value for the first observation and explain why zero would be wrong.
Show hint
The new key already represents one occurrence.
Show worked solution
Use and_modify(|n| *n += 1).or_insert(1). On a vacant key the modification closure is skipped, so inserting zero would undercount the first occurrence; one represents it correctly.
Check your solution
- A vacant key starts at 1
- An occupied key increments once
6. A default vector is expensive to construct. Compare or_insert(make_vector()) and or_insert_with(make_vector) for an already occupied key.
Show hint
One evaluates an argument before the call.
Show worked solution
or_insert evaluates make_vector() before checking the entry, even though the existing vector remains stored. or_insert_with calls its closure only for a vacant entry, avoiding that default construction on the occupied path.
Check your solution
- or_insert constructs the argument eagerly
- or_insert_with skips construction for an occupied entry
7. A report may show zero for a missing key but must distinguish an explicitly stored zero in an audit view. Describe both lookup policies.
Show hint
Retain Option until the caller selects its policy.
Show worked solution
For the report use get(key).copied().unwrap_or(0) without inserting a key. For audit, match Some(&0), Some(&n), and None separately so stored zero remains distinguishable from absence.
Check your solution
- The report can display zero without inserting
- The audit distinguishes Some(&0) from None
8. A map has key "x" with count 4. Compare inserting 1 with incrementing through entry, and give both possible final counts.
Show hint
insert replaces an existing value.
Show worked solution
insert("x", 1) replaces 4 with 1 and returns Some(4). An entry update that adds one instead changes the existing count from 4 to 5; choose according to the domain policy.
Check your solution
- Replacement leaves 1
- Incrementing leaves 5
9. An entry reference is used after a second entry call on the same map. Explain the conflict and redesign the updates for two independent counters.
Show hint
End one mutable reference’s use before taking another.
Show worked solution
Complete the first counter update and its last use, then call entry for the second key and update it. Keeping both mutable references live across the second call requests overlapping mutable access to the map.
Check your solution
- The first update finishes before the second borrow
- No two mutable entry references overlap
10. A u8 count is 254. Apply two checked increments, rejecting overflow without changing the value. Give both outcomes.
Show hint
Check before writing each new value.
Show worked solution
The first checked_add(1) returns Some(255), so store 255. The next returns None because 256 cannot fit; reject that update and retain 255 rather than wrapping or clamping silently.
Check your solution
- The first update stores 255
- The second fails and preserves 255
11. A map must survive after a reusable input buffer is cleared. Choose String or &str keys and explain the ownership consequence.
Show hint
The map cannot retain slices into invalidated buffer contents.
Show worked solution
Store owned String keys, creating or moving independent text before the buffer is cleared. Borrowed &str keys would depend on the buffer’s validity and cannot safely be used after a conflicting clear.
Check your solution
- The map owns String keys
- The keys remain independent of the cleared buffer
12. A HashMap<String, u32> contains "oak". Explain how to query it with &str without allocating a second String and how to handle absence.
Show hint
get supports a compatible borrowed key.
Show worked solution
Call map.get("oak") and match Some(count) and None. The string slice can look up the owned String key without constructing another String; the returned count is borrowed from the map.
Check your solution
- The lookup can use &str
- Both presence and absence are handled
13. Compare counts for ["A", "a", "A"] under case-sensitive keys and ASCII-lowercase normalization.
Show hint
Apply normalization before counting only in the second policy.
Show worked solution
Case-sensitive counting gives A: 2 and a: 1. ASCII lowercasing first maps all three to a, giving a: 3; that policy does not promise general Unicode case folding.
Check your solution
- Case-sensitive counts are A 2 and a 1
- ASCII-lowercase count is a 3
14. The tokenizer splits only on whitespace. For "tea, tea" explain the resulting keys and propose a policy if punctuation should be ignored.
Show hint
Whitespace splitting does not remove punctuation.
Show worked solution
The tokens are "tea," and "tea", so they are distinct keys without further normalization. Specify and apply a punctuation rule before entry if the domain intends them to count together.
Check your solution
- The original tokens are distinct
- A documented punctuation rule is applied before counting
15. A report needs alphabetical keys for counts pear: 2, apple: 1, plum: 3. Give the sequence and two suitable strategies.
Show hint
Separate map storage from presentation order.
Show worked solution
The key order is apple, pear, plum under Rust string ordering. Use BTreeMap for ordered traversal or collect HashMap keys and sort them before producing the report.
Check your solution
- The order is apple, pear, plum
- Either ordered storage or sorted keys provides it
16. A frequency test compares a formatted HashMap to one fixed unsorted string. Explain the defect and design a stable check for two keys.
Show hint
HashMap does not guarantee traversal order.
Show worked solution
Assert map.get("a") == Some(&2) and map.get("b") == Some(&1), plus map.len() == 2 when no other entries are allowed. Alternatively compare a sorted extracted representation for a report requirement.
Check your solution
- Counts are checked by key
- The length check detects unexpected extra keys
17. A custom key considers two IDs equal but hashes them differently. Explain why it is unsuitable for HashMap and how to repair the contract.
Show hint
Equal keys must have equal hashes.
Show worked solution
HashMap requires equal keys to hash equally. Define Eq and Hash using the same identity fields, then test equal ID values for equality and consistent hashing; also ensure stored key identity is not mutated.
Check your solution
- Equal keys use consistent hashing
- Stored key identity remains stable
18. A batch has two valid tokens followed by an invalid token, and policy requires no partial update. Design an in-memory commit strategy.
Show hint
Validate into temporary state before changing the live map.
Show worked solution
Build and validate a staged frequency map or staged changes first. If the third token is invalid, discard the staged state and keep the live map unchanged; commit only when the complete batch passes.
Check your solution
- The invalid batch leaves the live map unchanged
- The staged changes commit only after full validation
19. An untrusted stream can contain unlimited unique tokens. Name two independent resource limits and explain why memory safety alone is insufficient.
Show hint
Count distinct keys and constrain token or record sizes.
Show worked solution
Set a maximum number of distinct keys and a maximum token size, with a total-record limit if needed. A safe HashMap can still consume excessive memory when it stores unbounded distinct owned keys.
Check your solution
- Distinct keys are bounded
- Token size is bounded
20. A missing-key lookup must report an error instead of zero. Describe the Result conversion and an observable test.
Show hint
Attach a meaningful error to None.
Show worked solution
Convert map.get(key) with ok_or or ok_or_else to a Result carrying a MissingKey error. Test that an absent key returns that category and that the lookup does not add an entry.
Check your solution
- The absent key returns MissingKey
- The map length remains unchanged
Key takeaways
- Entry combines lookup with insertion or update.
- Handle absence and ordering as explicit contracts.
- entry updates a stored value but does not define counting policy by itself.
- A missing key and a stored zero are distinct until the caller chooses a fallback.
- HashMap ordering and unbounded resource use require explicit handling.