Module 5 • Lesson 25

HashMaps and HashSets

📚 9 min read💻 Free Course🦀 nixus.pro

HashMap: Key-Value Store

use std::collections::HashMap;

fn main() {
    let mut scores: HashMap = HashMap::new();
    scores.insert("Alice".to_string(), 10);
    scores.insert("Bob".to_string(), 20);

    // Access
    println!("{:?}", scores.get("Alice")); // Some(&10)
    println!("{}", scores.get("Alice").copied().unwrap_or(0));

    // entry() API - the key pattern
    let text = "hello world hello rust hello";
    let mut word_count: HashMap<&str, u32> = HashMap::new();
    for word in text.split_whitespace() {
        *word_count.entry(word).or_insert(0) += 1;
    }
    println!("{:?}", word_count);

    // Iterate
    let mut sorted: Vec<_> = word_count.iter().collect();
    sorted.sort_by_key(|&(k, _)| k);
    for (word, count) in sorted { println!("{}: {}", word, count); }

    // Remove and retain
    scores.remove("Bob");
    scores.retain(|_, v| *v > 5);
    println!("{:?}", scores);
}

// HashSet
use std::collections::HashSet;
fn demo_set() {
    let a: HashSet = [1,2,3,4,5].iter().cloned().collect();
    let b: HashSet = [3,4,5,6,7].iter().cloned().collect();
    let inter: HashSet<_> = a.intersection(&b).collect();
    let union: HashSet<_> = a.union(&b).collect();
    let diff: HashSet<_>  = a.difference(&b).collect();
    println!("inter={:?} union={:?} diff={:?}", inter, union, diff);
}

🎯 Practice

  1. Count character frequency in a string using HashMap<char, usize>
  2. Find the most common word in a paragraph
  3. Given two Vec<String>, find common elements using HashSet intersection
  4. Implement a simple in-memory key-value store struct wrapping HashMap

🎉 Key Takeaways