HashMap Basics
A hash map stores key-value pairs and allows fast insertion, lookup, and removal based on keys. In Rust, HashMap<K, V> from the standard library provides a safe, efficient, and ergonomic implementation of a hash table.
This section covers the core operations you’ll use most often.
Importing HashMap
HashMap lives in the std::collections module.
use std::collections::HashMap;
Creating a HashMap
You can create an empty hash map using HashMap::new().
let mut map: HashMap<String, i32> = HashMap::new();
Rust requires the key type to implement Eq and Hash.
Inserting Key-Value Pairs
Use insert to add entries to the map.
map.insert("apple".to_string(), 3);
map.insert("banana".to_string(), 5);
If the key already exists, the value is updated.
Retrieving Values
Use get to retrieve a value by key.
if let Some(value) = map.get("apple") {
println!("Apple count: {}", value);
}
get returns an Option<&V> because the key may not exist.
Checking for Keys
Use contains_key to check if a key exists.
if map.contains_key("banana") {
println!("Banana exists");
}
Removing Entries
Use remove to delete a key-value pair.
map.remove("banana");
Iterating Over a HashMap
You can iterate over key-value pairs using a for loop.
for (key, value) in &map {
println!("{} → {}", key, value);
}
Iteration order is not guaranteed.
Updating Values Safely (entry API)
The entry API is useful for conditional insertion or update.
Insert if Missing
map.entry("orange".to_string()).or_insert(1);
Update Existing Value
map.entry("apple".to_string()).and_modify(|v| *v += 1);
Common Pattern: Frequency Counting
let text = "hello world";
let mut freq = HashMap::new();
for ch in text.chars() {
*freq.entry(ch).or_insert(0) += 1;
}
println!("{:?}", freq);
Example Usage
fn main() {
let mut scores = HashMap::new();
scores.insert("Alice", 90);
scores.insert("Bob", 85);
println!("Alice: {:?}", scores.get("Alice"));
scores.entry("Bob").and_modify(|v| *v += 5);
for (name, score) in &scores {
println!("{} → {}", name, score);
}
}
Time and Space Complexity
Time Complexity (Average Case)
| Operation | Complexity |
|---|---|
| Insert | O(1) |
| Lookup | O(1) |
| Remove | O(1) |
Worst-case complexity can degrade to O(n), but this is rare and mitigated by good hashing.
Space Complexity
| Space | Complexity | Reason |
|---|---|---|
| HashMap storage | O(n) | Store key-value pairs |
Important Notes
- Keys must implement
EqandHash - HashMap does not preserve order
- Use
BTreeMapif sorted order is required
Summary
HashMapprovides fast key-based access- Core operations are simple and expressive
entryAPI avoids repetitive checks- One of the most practical data structures in Rust