🎓 A1Learner
🔍

Rust HashMap Views & Removal

HashMap views are tools that answer questions about the whole map. keys() lists the keys, values() lists the values, and remove() takes one pair out of the map.

Ask whether a key exists

The use line from Rust HashMap stays at the top of the file. contains_key answers yes or no, without handing you the value:

let mut scores = HashMap::new();
scores.insert("Blue", 10);
println!("has Blue = {}", scores.contains_key("Blue"));
println!("has Red = {}", scores.contains_key("Red"));

See every key with keys()

keys() walks the keys only. The order is not promised, so this snippet collects and sorts them before printing:

let mut scores = HashMap::new();
scores.insert("Yellow", 50);
scores.insert("Blue", 10);
let mut keys: Vec<&str> = scores.keys().copied().collect();
keys.sort();
println!("keys = {:?}", keys);

See every value with values()

values() walks the values only — perfect for adding them all up:

let mut scores = HashMap::new();
scores.insert("Yellow", 50);
scores.insert("Blue", 10);
let total: i32 = scores.values().sum();
println!("total = {}", total);

Take a pair out with remove()

remove takes the whole pair out and hands the value back as an Option. A second try finds nothing:

let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 50);
let taken = scores.remove("Blue");
println!("taken = {:?}, left = {}", taken, scores.len());
println!("again = {:?}", scores.remove("Blue"));

Count the pairs, or clear them all

len counts the pairs, is_empty asks whether any are left, and clear takes them all out at once:

let mut scores = HashMap::new();
scores.insert("Blue", 10);
scores.insert("Yellow", 50);
println!("{} pairs, empty = {}", scores.len(), scores.is_empty());
scores.clear();
println!("after clear: {} pairs, empty = {}", scores.len(), scores.is_empty());

Example

use std::collections::HashMap;

fn main() {
    let mut prices: HashMap<&str, i32> = HashMap::new();
    prices.insert("apple", 30);
    prices.insert("banana", 12);
    prices.insert("cherry", 45);
    println!("items = {}", prices.len());
    let mut names: Vec<&str> = prices.keys().copied().collect();
    names.sort();
    println!("names = {:?}", names);
    let total: i32 = prices.values().sum();
    println!("total price = {}", total);
    let gone = prices.remove("banana");
    println!("removed = {:?}, banana back = {}", gone, prices.contains_key("banana"));
}

Key points

  • Each view tool answers one question about the whole map.
  • Use contains_key(key) to ask whether a key is present, without taking its value out
  • Use keys() to walk over just the keys, and values() to walk over just the values
  • Use remove(key) to take a pair out.
  • remove(key) gives back an Option.
  • Some(value) comes back when the key was there.
  • None comes back when the key was not there.
  • Use len() to count the pairs.
  • Use is_empty() to ask whether the map holds nothing.
  • Use clear() to remove every pair at once.

In this example, prices maps three fruits to their prices. len() counts 3 items. keys() gathers the names into a Vec. sort() puts them in alphabetical order before printing. The map itself promises no order. values().sum() adds the prices: 30 + 12 + 45 = 87. remove("banana") takes that pair out and gives back Some(12), and the last check shows contains_key("banana") is now false.

Note

keys() and values() visit in the same unpromised order as the map itself.

Collect the keys into a Vec and sort them when the order matters, as the snippets do.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

What does map.remove(key) give back when the key is not in the map?