Module 4HashMap: Add, Get, RemoveLesson 7 of 2322 min
HashMap Insert, Get, Update
insert, get, get_mut, contains_key — and owned String keys.
Create & insert
rust
use std::collections::HashMap;
fn main() {
let mut m: HashMap<String, i32> = HashMap::new();
m.insert("alice".into(), 10);
m.insert("bob".into(), 7);
println!("alice={:?}", m.get("alice"));
println!("carol={:?}", m.get("carol"));
println!("has bob={}", m.contains_key("bob"));
}Output
alice=Some(10)
carol=None
has bob=trueGet
rust
m.get("alice") // Option<&i32>
m.get_mut("alice") // Option<&mut i32>
m.contains_key("bob")Update patterns
rust
*m.entry("alice".into()).or_insert(0) += 5;
// or
if let Some(v) = m.get_mut("bob") { *v += 1; }Iteration
rust
use std::collections::HashMap;
fn main() {
let mut m: HashMap<String, i32> = HashMap::new();
m.insert("alice".into(), 10);
m.insert("bob".into(), 7);
let mut keys: Vec<_> = m.keys().cloned().collect();
keys.sort(); // stable demo — HashMap itself is unordered
for k in keys {
println!("{k} {}", m[&k]);
}
}Output
alice 10
bob 7Order is random — sort keys if you need stable output.
Complexity
Average O(1) insert/get/remove.
Challenge
Use entry API to set default 0 then += 1 for keys in ["a","b","a","c","a"].
Tips
- get returns Option
- entry avoids double lookup
- HashMap order is unstable
Try it live
HashMap Insert, Get, UpdateRust 2021
Loading editor…
Output
Press Run to compile and execute.