Lesson 20 of 20
HashMaps
HashMap<K, V>
HashMap stores key-value pairs with O(1) average-case lookup.
Creating a HashMap
use std::collections::HashMap;
let mut scores: HashMap<String, i32> = HashMap::new();
Inserting and Accessing
scores.insert(String::from("Alice"), 10);
scores.insert(String::from("Bob"), 20);
// Access — panics if key missing
println!("{}", scores["Alice"]);
// Safe access
if let Some(score) = scores.get("Alice") {
println!("{}", score);
}
Entry API
// Insert if not present
scores.entry(String::from("Alice")).or_insert(50);
// Modify existing or insert new
let count = map.entry(word).or_insert(0);
*count += 1;
Iterating
for (key, value) in &scores {
println!("{}: {}", key, value);
}
Note: HashMap iteration order is non-deterministic. Do not rely on order.
Other Methods
scores.contains_key("Alice") // true
scores.remove("Bob") // removes, returns Option<V>
scores.len() // number of entries
Your Task
word_count(text: &str) -> HashMap<&str, usize>— count occurrences of each word.two_sum(nums: &[i32], target: i32) -> Option<(usize, usize)>— find two indices that sum to target.most_frequent(v: &[i32]) -> i32— returns the most frequently occurring element.
Rust (Miri) loading...
Loading...
Click "Run" to execute your code.