HashMap::contains_key() / remove() / entry()
Rust's HashMap provides contains_key() to check whether a key exists, remove() to delete an entry, and the entry().or_insert() pattern to insert a value only if the key is absent.
Syntax
use std::collections::HashMap;
// Check if a key exists (returns bool).
let exists = map.contains_key("apple");
// Remove a key and its value (returns Option<V>).
let removed = map.remove("apple"); // Some(value) or None
// entry API: insert if the key does not exist.
map.entry("key".to_string()).or_insert(0);
// entry API: update an existing value.
let count = map.entry("key".to_string()).or_insert(0);
*count += 1; // Increment the value.
Method List
| Method | Description |
|---|---|
| map.contains_key(&key) | Returns true if the key exists. |
| map.contains_value(&value) | Returns true if the value exists (note: HashMap has no built-in method for this; a manual check is required). |
| map.remove(&key) | Removes the key and returns its value wrapped in Some, or None if not found. |
| map.remove_entry(&key) | Removes and returns the key-value pair as a tuple. |
| map.entry(key) | Returns an entry for the key (either OccupiedEntry or VacantEntry). |
| .or_insert(value) | Inserts the value if the entry is vacant, then returns a mutable reference to the value. |
| .or_insert_with(|| ...) | Inserts the return value of a closure if the entry is vacant. |
| .or_default() | Inserts the default value (via Default::default()) if the entry is vacant. |
| .and_modify(|v| ...) | Applies a closure to the value only if the entry is occupied. |
| map.retain(|k, v| ...) | Retains only the entries that satisfy the given predicate. |
Sample Code
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, i32> = HashMap::new();
map.insert("apple".to_string(), 3);
map.insert("banana".to_string(), 5);
map.insert("cherry".to_string(), 2);
// Check for a key with contains_key().
println!("apple exists?: {}", map.contains_key("apple")); // true
println!("grape exists?: {}", map.contains_key("grape")); // false
// Remove an entry with remove().
let removed = map.remove("banana");
println!("Removed value: {:?}", removed); // Some(5)
println!("Length after removal: {}", map.len()); // 2
let none = map.remove("grape"); // Key does not exist.
println!("Remove non-existent key: {:?}", none); // None
// --- entry API ---
// Count word occurrences (a classic use case for the entry API).
let text = "hello world hello rust hello world";
let mut counts: HashMap<String, i32> = HashMap::new();
for word in text.split_whitespace() {
let count = counts.entry(word.to_string()).or_insert(0);
*count += 1; // Increment the value through the mutable reference.
}
println!("Word counts: {:?}", counts);
// Use or_default() to insert the Default trait's default value.
let mut vmap: HashMap<String, Vec<i32>> = HashMap::new();
vmap.entry("evens".to_string()).or_default().push(2);
vmap.entry("evens".to_string()).or_default().push(4);
vmap.entry("odds".to_string()).or_default().push(1);
println!("Groups: {:?}", vmap);
// Use and_modify() to update only existing values.
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert("Alice".to_string(), 90);
scores.entry("Alice".to_string()).and_modify(|s| *s += 10);
scores.entry("Bob".to_string()).and_modify(|s| *s += 10).or_insert(0);
println!("scores: {:?}", scores); // Alice: 100, Bob: 0
// Use retain() to keep only entries that satisfy a condition.
let mut m: HashMap<&str, i32> = [("a", 1), ("b", 2), ("c", 3), ("d", 4)]
.iter().cloned().collect();
m.retain(|_, v| *v >= 3); // Keep only entries with value >= 3.
println!("retain (value >= 3): {:?}", m);
}
Notes
The entry API is one of the most idiomatic patterns in Rust's HashMap. It lets you safely and efficiently express "insert if absent, update if present" logic, and is commonly used for aggregation tasks such as counting word occurrences.
or_insert() returns a mutable reference (&mut V) to the value. You can use this reference to modify the value in place, making it easy to increment a counter or append to a vector.
For creating a HashMap and performing basic operations, see HashMap::new() / insert() / get(). For iterating over a HashMap, see HashMap::keys() / values() / iter().
If you find any errors or copyright issues, please contact us.