Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Collections: HashMap | Rust Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Rust Fundamentals

Lesson 17 of 50

·rust

Collections: HashMap

15 minutes

Course progress34%

Collections: HashMap

HashMap<K, V> stores key-value pairs. It's an unordered collection, making lookups very fast on average.

Creating HashMaps

use std::collections::HashMap;

fn main() {
    // Empty map
    let mut scores: HashMap<, > = HashMap::();
    
    
    scores.(::(\
String
u32
new
// Add key-value pairs
insert
String
from
"Alice\"), 10); scores.insert(String::from(\"Bob\"), 20); // From vectors (requires tuples) let teams = vec![(String::from(\"Red\"), 100), (String::from(\"Blue\"), 50)]; let map: HashMap<_, _> = teams.into_iter().collect(); }

Accessing Values

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(String::from(\"color\"), String::from(\"blue\"));
    
    // get() returns Option
    if let Some(value) = map.get(\"color\") {
        println!(\"Color: {}\", value);
    }
    
    // get_mut() for mutable access
    if let Some(value) = map.get_mut(\"color\") {
        *value = String::from(\"red\");
    }
    
    // Check existence
    if map.contains_key(\"color\") {
        println!(\"Color exists\");
    }
}

Iteration

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(\"a\", 1);
    map.insert(\"b\", 2);
    
    // Iterate over references
    for (key, value) in &map {
        println!(\"{}: {}\", key, value);
    }
    
    // Iterate with mutable values
    for value in map.values_mut() {
        *value += 1;
    }
    
    // Iterate keys only
    for key in map.keys() {
        println!(\"Key: {}\", key);
    }
}

Entry API or Updating Values

use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert(String::from(\"a\"), 1);
    
    // Update if exists, insert if not
    *map.entry(String::from(\"a\")).or_insert(0) += 1;
    *map.entry(String::from(\"b\")).or_insert(0) += 1;
    
    println!(\"{:?}\", map);  // {\"a\": 2, \"b\": 1}
}

Practical Example: Word Frequency

use std::collections::HashMap;

fn count_words(text: &str) -> HashMap<&str, i32> {
    let mut counts = HashMap::new();
    
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }
    
    counts
}

fn main() {
    let text = \"hello world hello rust world\";
    let counts = count_words(text);
    
    for (word, count) in counts {
        println!(\"{}: {}\", word, count);
    }
}

Key Requirements

Keys must implement:

  • Eq: Equality comparison
  • Hash: Hashability

Most common types already implement these: String, integers, booleans.

Performance

  • Average case: O(1) insertion, lookup, deletion
  • Worst case: O(n) (hash collisions)
  • Good hash functions make worst case rare

HashMap Downsides

  • Unordered: No guaranteed iteration order
  • Slower than BTreeMap for ordered operations
  • More memory overhead than vectors
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities
Previous lessonCollections: VecContinue to lesson 18Error Handling with OptionBack to Rust Fundamentals curriculum