Use HashMap::entry with or_insert to efficiently get or create a value for a key in a single operation.
Use the entry method on a HashMap to get a mutable reference to a value, inserting a default if the key is missing, then modify it directly. This pattern avoids multiple lookups and handles both insertion and update in one step.
use std::collections::HashMap;
let mut map = HashMap::new();
for word in "hello world wonderful world".split_whitespace() {
let count = map.entry(word).or_insert(0);
*count += 1;
}
println!("{map:?}");
The Entry API lets you check if a key exists in a map and update or add its value in one go, without looking it up twice. Think of it like a librarian who either hands you a book if it's on the shelf or pulls a new one from storage if it's missing, then lets you write in it immediately. You use this when you need to count items, aggregate data, or ensure a key exists before modifying it.