Hash Maps and Hash Sets

HashMap Iteration

HashMap<K, V> provides iterators over key-value pairs, keys alone, or values alone—by shared reference, mutable reference, or owned value—scanning the table's populated buckets in $O(\text{capacity})$ time.

Complete Reference of HashMap<K, V> Iterators

Method / for Syntax Receiver Yielded Item Type Map After Iteration
map.iter() or for (k, v) in &map &self (&K, &V) Intact
map.iter_mut() or for (k, v) in &mut map &mut self (&K, &mut V) Values modified in place
map.into_iter() or for (k, v) in map self (K, V) Consumed
map.keys() &self &K Intact
map.into_keys() self K Consumed
map.values() &self &V Intact
map.values_mut() &mut self &mut V Values modified in place
map.into_values() self V Consumed
map.drain() &mut self (K, V) Emptied (len = 0), capacity retained
map.extract_if(pred) &mut self (K, V) (where pred(&K, &mut V) is true) Matching entries removed; rest kept

Notice that iter_mut() yields (&K, &mut V)—never (&mut K, &mut V)—because mutating a key in place could alter its hash code and invalidate its bucket position.

Iterating Over Keys, Values, and Mutable Values

use std::collections::HashMap;

fn main() {
    let mut prices = HashMap::from([
        ("keyboard", 80_u32),
        ("monitor", 250),
        ("mouse", 40),
    ]);

    // 1. Apply a 10% discount to all values in place using `values_mut()`:
    for price in prices.values_mut() {
        *price = (*price * 90) / 100;
    }

    // 2. Sum all values using `values()`:
    let total: u32 = prices.values().sum();
    println!("Total after discount: ${total}");

    // 3. Collect and sort pairs when deterministic display order is needed:
    let mut sorted_items: Vec<(&str, u32)> = prices.into_iter().collect();
    sorted_items.sort_unstable_by_key(|&(name, _)| name);
    println!("Sorted items: {sorted_items:?}");
}
Total after discount: $333
Sorted items: [("keyboard", 72), ("monitor", 225), ("mouse", 36)]

Nondeterministic Iteration Order

Because RandomState seeds each HashMap instance with fresh random keys and SwissTable places items based on their randomized hashes, iterating over a HashMap produces elements in an arbitrary, nondeterministic order that varies across program runs (and even after rehashing the same map). Never rely on HashMap iteration order in tests or serialized outputs; either sort the collected entries or use BTreeMap<K, V>.