[Avg. reading time: 11 minutes]

Hash Map

A HashMap is a data structure for storing key-value pairs with fast lookup by key. You use it when you want to map a unique key (like a name) to a value (like a phone number) and retrieve it efficiently.

  • Stores data as Key : Value
  • Keys are used to look up corresponding values
  • Uses hashing to decide where each entry lives internally
  • Dynamically resizes to maintain good performance as it grows
  • Non-sequential: iteration order is not guaranteed

Real-World Example

Phone book

  • Key: person’s name
  • Value: phone number

A hash function helps the program find the phone number quickly.

Other languages call this:

  • Map
  • Dictionary
  • Associative Array

Rules

  • All keys must have the same data type.
  • All values must have the same data type.
  • Each key can have only one value at a time.
  • No duplicate keys.

Hashing

Hashing transforms input data (like a string) into a fixed-size number called a hash value.

MD5 Hash Generator

  • Fixed-size output: input size doesn’t matter, output size stays the same
  • Fast: designed to be efficient
  • Collisions can happen: different inputs may produce the same hash value

Hasing Example

use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};

fn main() {
    let s = "hello world";

    let mut hasher = DefaultHasher::new();
    s.hash(&mut hasher);

    let hash_value = hasher.finish();
    println!("Hash value for '{}': {}", s, hash_value);
}

HashMap Example

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullica Hill", 25000);
    cities.insert("Swedesboro", 28000);

    println!("cities: {:?}, {:?}", cities, cities.get("Glassboro"));
}

Insert

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullicahill", 25000);
    cities.insert("Swedesboro", 28000);
   
    println!("cities is {:?}", cities);

    //Insert Value
    cities.insert("Paulsboro", 11000);

    // Update Existing Value
    cities.insert("Glassboro", 31000);

	println!("cities is {:?}", cities);
}

Insert/Update/Get

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullica Hill", 25000);
    cities.insert("Swedesboro", 28000);

    // Option 1: overwrite existing value
    cities.insert("Glassboro", 31000);

    // Option 2: insert only if missing
    cities.entry("Deptford").or_insert(12000);

    // Option 3: update a value in-place
    let gpopulation = cities.entry("Glassboro").or_insert(0);
    *gpopulation += 1;

    println!("cities: {:?}", cities);

    match cities.get("Glassboro") {
        Some(pop) => println!("Glassboro population: {}", pop),
        None => println!("Glassboro population not available"),
    }
}

Remove

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullicahill", 25000);
    cities.insert("Swedesboro", 28000);

    // Remove an entry
    cities.remove("Mullicahill");

    println!("After removal: {:?}", cities);
}

Iterating Over the HashMap

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullicahill", 25000);
    cities.insert("Swedesboro", 28000);

    // Iterating over the HashMap
    for (city, population) in &cities {
        println!("The population of {} is {}", city, population);
    }
}

Check for Existence

use std::collections::HashMap;

fn main() {
    let mut cities = HashMap::new();
    cities.insert("Glassboro", 30000);
    cities.insert("Mullicahill", 25000);
    cities.insert("Swedesboro", 28000);

    // Checking if a key exists
    if cities.contains_key("Swedesboro") {
        println!("Swedesboro is in the HashMap");
    } else {
        println!("Swedesboro is not in the HashMap");
    }
}

Merge

use std::collections::HashMap;

fn main() {
    let mut cities1 = HashMap::new();
    cities1.insert("Glassboro", 30000);
    cities1.insert("Mullicahill", 25000);

    let mut cities2 = HashMap::new();
    cities2.insert("Swedesboro", 28000);
    cities2.insert("Depford", 12000);

    // Merging two HashMaps
    for (city, population) in cities2 {
        cities1.insert(city, population);
    }

    println!("Merged cities: {:?}", cities1);
}

#hashmapVer 2.0.12

Last change: 2026-02-18