Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust HashMap iteration

Reference for iterating a Rust HashMap: iter, iter_mut, keys, values, values_mut, into_iter, drain, extract_if alternatives and the unspecified order.

A HashMap<K, V> can be walked in several ways. iter() yields (&K, &V) pairs, iter_mut() yields (&K, &mut V), keys() and values() yield one side only, values_mut() lets you edit values in place, into_iter() consumes the map, and drain() empties it while yielding owned pairs but keeps the allocation.

The order is arbitrary and different for every map and every run. Code that prints a map or compares output must sort first (or use a BTreeMap).

Rust
for (k, v) in &map { /* &K, &V */ }
for v in map.values_mut() { /* &mut V */ }

Try it

Rust Reading a map in a stable order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Mutating and draining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub fn iter(&self) -> Iter<'_, K, V>               // Item = (&K, &V)
pub fn iter_mut(&mut self) -> IterMut<'_, K, V>    // Item = (&K, &mut V)
pub fn keys(&self) -> Keys<'_, K, V>               // Item = &K
pub fn values(&self) -> Values<'_, K, V>           // Item = &V
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> // Item = &mut V
pub fn into_keys(self) -> IntoKeys<K, V>           // Item = K
pub fn into_values(self) -> IntoValues<K, V>       // Item = V
pub fn drain(&mut self) -> Drain<'_, K, V>         // Item = (K, V)
// IntoIterator: for &HashMap, &mut HashMap and HashMap
Name Description
iter, iter_mut Borrow the map and yield key/value pairs.
keys, values, values_mut One side only; keys are never mutable.
into_iter, into_keys, into_values Consume the map and yield owned items.
drain Removes all pairs, yielding them; the map keeps its capacity.

Returns: iterators that report an exact size_hint and implement ExactSizeIterator, but not DoubleEndedIterator (a hash table has no meaningful "last").

Errors and panics: none. If you drop a Drain before it is exhausted, the remaining pairs are still removed.

Usage notes

  • Order is unspecified, and with the default RandomState it differs between two maps with identical contents. Sort, or use BTreeMap.
  • You cannot add or remove while iterating because the iterator borrows the map. Collect the keys first (let ks: Vec<_> = m.keys().cloned().collect();) or use retain.
  • for (k, v) in &map is the idiomatic spelling of iter(); for (k, v) in &mut map is iter_mut().
  • Keys are immutable while in the map; changing one would break the hash invariant. That is why there is no keys_mut.
  • Cost: iteration is O(capacity), not O(len), so a map that once held a million entries and is now nearly empty still walks its large table. Call shrink_to_fit() after mass removal.
  • retain filters in place; HashMap::extract_if (stable since 1.88) removes matching pairs and yields them.
  • Collecting back: iter().map(...).collect::<HashMap<_, _>>() rebuilds a map from transformed pairs.