Sub topic 12
Iterating over keys, values and pairs
This chapter assumes you can create a HashMap, insert and read entries, and write a for loop over a Vec. It also assumes you know the difference between &, &mut and moving a value. A HashMap<K, V> can be walked in several ways. The method you pick decides whether you see keys, values or both, and whether you borrow the map or consume it.
The default: pairs by reference
A for loop over &map yields (&K, &V) tuples. Calling map.iter() does the same thing.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 3);
stock.insert("pear".to_string(), 0);
stock.insert("plum".to_string(), 12);
// Order is unspecified and can differ between runs.
for (name, count) in &stock {
println!("{name}: {count}");
}
let total: u32 = stock.values().sum();
println!("total {total}"); // total 15
let mut names: Vec<&String> = stock.keys().collect();
names.sort();
println!("{:?}", names); // ["apple", "pear", "plum"]
}Both name and count are references into the map. The map stays usable after the loop because the loop only borrowed it.
The six ways to iterate
Each method differs in what it yields and whether it consumes the map.
| Method | Item type | Map afterwards |
|---|---|---|
| `iter()` or `&map` | `(&K, &V)` | Usable |
| `iter_mut()` or `&mut map` | `(&K, &mut V)` | Usable |
| `keys()` | `&K` | Usable |
| `values()` | `&V` | Usable |
| `values_mut()` | `&mut V` | Usable |
| `into_iter()` or `map` | `(K, V)` | Moved |
Two more consuming methods, into_keys() and into_values(), yield K and V alone and also move the map. drain() yields (K, V) but only borrows the map mutably. It empties the map and leaves it usable.
Changing values while iterating
Keys are never mutable through an iterator. Changing a key would change its hash and corrupt the table. So iter_mut() gives &K paired with &mut V. If you only need the values, values_mut() is simpler.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 3);
stock.insert("pear".to_string(), 0);
stock.insert("plum".to_string(), 12);
for count in stock.values_mut() {
*count += 1;
}
for (name, count) in stock.iter_mut() {
if name.starts_with('p') {
*count *= 2;
}
}
let mut pairs: Vec<_> = stock.iter().collect();
pairs.sort();
println!("{:?}", pairs); // [("apple", 4), ("pear", 2), ("plum", 26)]
}You must write *count to reach the number, because count is a &mut u32. Forgetting the * is the most common compile error with values_mut().
Order is not guaranteed
HashMap iteration order depends on the hash function and the internal layout. The standard hasher is seeded randomly per map. Two runs of the same program can print entries in different orders. Never write a test that compares printed output of an unsorted map.
You have three options when order matters:
- Collect the keys or pairs into a
Vecand sort it, as shown above. - Sort by value with a comparator, breaking ties by key so the result is deterministic.
- Use a
BTreeMap, which always iterates in key order, at the cost of slower lookups.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<&str, u32> = HashMap::new();
scores.insert("Ana", 30);
scores.insert("Bo", 25);
scores.insert("Cy", 30);
let mut ranked: Vec<(&&str, &u32)> = scores.iter().collect();
ranked.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (name, score) in ranked {
println!("{name}: {score}");
}
// Ana: 30
// Cy: 30
// Bo: 25
}The type &&str appears because the keys are &str and iter() adds one more reference. Printing and comparing both work through it.
Consuming the map
When you no longer need the map, into_iter() hands you owned keys and values. This avoids cloning, which matters for String and Vec values.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, Vec<u32>> = HashMap::new();
stock.insert("apple".to_string(), vec![1, 2]);
stock.insert("plum".to_string(), vec![3]);
let mut flat: Vec<(String, Vec<u32>)> = stock.into_iter().collect();
flat.sort();
println!("{:?}", flat); // [("apple", [1, 2]), ("plum", [3])]
// stock has been moved and cannot be used here.
}into_keys() and into_values() are the same idea when you want only one side. Use them in place of into_iter().map(|(k, _)| k).
Modifying the map structure during iteration
You cannot insert or remove entries while iterating over the same map. The iterator holds a borrow of the map, so map.insert(...) inside the loop fails to compile. This is the same rule that stops you pushing to a Vec while holding a reference into it.
There are two standard ways around it.
If the goal is to drop entries that match a condition, use retain. Its closure receives (&K, &mut V) and keeps the entry when the closure returns true.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 4);
stock.insert("pear".to_string(), 2);
stock.insert("plum".to_string(), 26);
stock.retain(|_, count| *count > 2);
println!("{}", stock.len()); // 2
}If the change depends on other work, such as inserting derived entries, collect the keys first. The collected keys no longer borrow the map, so the loop that follows may modify it.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 4);
stock.insert("pear".to_string(), 0);
let empty: Vec<String> = stock
.iter()
.filter(|(_, c)| **c == 0)
.map(|(k, _)| k.clone())
.collect();
for name in empty {
stock.remove(&name);
stock.insert(format!("{name}-restock"), 10);
}
let mut keys: Vec<_> = stock.keys().collect();
keys.sort();
println!("{:?}", keys); // ["apple", "pear-restock"]
}The clone copies each matching key once. That cost is the price of releasing the borrow.
Common mistakes
- Relying on order. A test that passes once and fails later usually has an unsorted map in it.
- Missing the dereference.
*count += 1is required withvalues_mut()anditer_mut(). Comparisons such as**c == 0throughfilterneed extra stars becausefilteradds a reference to the item. - Using the map after a
forloop overmap. Writingfor (k, v) in mapmoves the map. Writefor (k, v) in &mapto borrow it. - Cloning when sorting. Sorting a
Vec<(&K, &V)>needs no clones. Clone only when the data must outlive the borrow. - Expecting stable order after mutation. Inserting or removing can reorder a hash map's internal layout, so iteration order may change even within one run.
Exercise
You have a HashMap<String, u32> named inventory. Write a loop that doubles every value, then print the keys in alphabetical order. Which methods do you use, and why can't you just print inventory.keys() directly?
Show answer
Use for v in inventory.values_mut() { *v *= 2; } to change values in place. Then collect with let mut keys: Vec<&String> = inventory.keys().collect(); keys.sort(); and print keys. Printing inventory.keys() directly gives the keys in an unspecified order that can change between runs, so you must sort them first.
Exercise
A colleague writes for (name, n) in &stock { if *n == 0 { stock.remove(name); } } and gets a compile error. Why does it fail, and what is a one-line fix?
Show answer
The loop holds a shared borrow of stock through its iterator, and remove needs a mutable borrow at the same time, which the borrow checker rejects. The one-line fix is stock.retain(|_, n| *n != 0);, which removes the zero entries without a separate loop.