HashMap::keys() / values() / iter()
Methods for iterating over the keys, values, or key-value pairs of a HashMap. Use these methods when you need to process the contents of a map in a loop.
Syntax
// Returns an iterator over references to each key.
for key in map.keys() { }
// Returns an iterator over references to each value.
for value in map.values() { }
// Returns an iterator over key-value pairs as tuples.
for (key, value) in map.iter() { }
// Returns an iterator that consumes the map, yielding owned key-value pairs.
for (key, value) in map.into_iter() { }
Method List
| Method | Description |
|---|---|
| keys() | Returns an iterator over references to each key. Use this when you only need to process keys without touching the values. |
| values() | Returns an iterator over references to each value. Use this when you only need to process values and do not need the keys. |
| values_mut() | Returns an iterator over mutable references to each value. Use this when you need to modify values inside a loop. |
| iter() | Returns an iterator over key-value pairs as (&K, &V) tuples. This is the most commonly used iteration method. |
| iter_mut() | Returns an iterator over pairs of a key reference and a mutable value reference as (&K, &mut V) tuples. |
| into_iter() | Returns an iterator yielding owned key-value pairs as (K, V) tuples. The map cannot be used after calling this method. |
Sample Code
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
scores.insert(String::from("Carol"), 92);
// Loop over keys only.
println!("--- keys ---");
for key in scores.keys() {
println!("{}", key);
}
// Loop over values only.
println!("--- values ---");
for val in scores.values() {
println!("{}", val);
}
// Loop over key-value pairs.
println!("--- iter ---");
for (name, score) in scores.iter() {
println!("{}: {}", name, score);
}
// Get mutable references to values and modify them.
for val in scores.values_mut() {
*val += 5; // Add 5 points to every score.
}
println!("After adding points: {:?}", scores);
}
Overview
Choose among three iteration methods depending on your needs: use keys() when you only need the keys, values() when you only need the values, and iter() when you need both. Note that HashMap does not preserve insertion order — the iteration order depends on hash values and may differ between runs.
To modify values during iteration, use values_mut() or iter_mut(). If you no longer need the map after the loop, use into_iter() to take ownership of the entries directly, which can be more efficient. Keep in mind that the map becomes unavailable after calling into_iter().
If you find any errors or copyright issues, please contact us.