RRust By Example
intermediateCollections

HashMap Advanced Operations

Merge, update, and transform HashMaps.

HashMap Advanced Operations

Merge, update, and transform HashMaps.

Difficulty

Intermediate

Code

rust
use std::collections::HashMap;

fn main() {
    let mut a: HashMap<&str, i32> = HashMap::new();
    a.insert("x", 1);
    a.insert("y", 2);

    let mut b: HashMap<&str, i32> = HashMap::new();
    b.insert("y", 3);
    b.insert("z", 4);

    // merge b into a, summing values for duplicate keys
    for (k, v) in b {
        *a.entry(k).or_insert(0) += v;
    }
    println!("merged: {:?}", a);

    // retain only entries where value > 2
    a.retain(|_, v| *v > 2);
    println!("retained: {:?}", a);

    // drain all entries
    let drained: Vec<_> = a.drain().collect();
    println!("drained: {:?}", drained);
    println!("a after drain: {:?}", a);
}

Explanation

Advanced HashMap: drain, retain, entry API updates.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples