By the end of this lesson
Count repeated keys without relying on random iteration order.
Before you start
- Rust 1.90.0 or later, a terminal and a plain-text editor. Examples were tested with Rust 1.90.0, Edition 2024 on Linux.
- Complete lesson 18, or be comfortable explaining and running its examples.
Three words to know
- Map
- A collection associating keys with values.
- Entry
- An API for updating a present or absent key.
- Deterministic output
- The same ordered output for the same validated input.
1. Understand the idea
HashMap is useful for fast lookup, but its iteration order is not a stable report format. BTreeMap keeps keys in sorted order. Select a collection or sort explicitly when users compare reports. entry(key).or_insert(0) provides mutable access to a counter whether or not the key was already present.
2. Save, run and observe
Save this complete program as lesson.rs in a fresh practice folder. It replaces that lesson file only; keep earlier examples separately. Compile it with rustc, then run the executable. Rust source goes in the editor; rustc and cargo commands go in the terminal.
use std::collections::BTreeMap;
fn main() {
let mut counts = BTreeMap::new();
for status in ["open", "closed", "open"] {
*counts.entry(status).or_insert(0_u32) += 1;
}
for (status, count) in counts { println!("{status}={count}"); }
}
What you should see · example output
closed=1 open=2
rustc --edition=2024 lesson.rs -o lesson
./lesson3. Explain the result
The star dereferences the mutable counter so += changes the stored number. Each repeated key increases the existing value. The final loop consumes this map, which is fine because it is not used afterwards. Our two-status final project can instead use named counters and a fixed output order.
YOUR TURN
A small check before you continue
Would changing BTreeMap to HashMap guarantee closed prints first?
Show a suggested answer
No. Do not assert a particular HashMap iteration order; sort the output or use an ordered collection.
Sources and scope
Documentation and examples reviewed 2026-10-18. Provider screens, package versions and output wording can differ. Examples show expected outcomes; they are not a claim that OpenViST connected to your server or verified your setup.
