liveBook · Manning

BTreeMap

As explained in Learn Rust in a Month of Lunches

BTreeMap is Rust's ordered map collection that associates keys with values and iterates them in key order.

BTreeMap is Rust’s ordered map: it associates keys with values and yields entries in key order. It uses method names and signatures similar to HashMap, so changing a simple map usually requires only changing the type name. section 6.1.1

Ordering population data

Store years and populations in a BTreeMap, insert 2020, 1372, and 1851, then iterate over the entries. The output is ordered by year: 1372, 1851, and 2020. section 6.1.1

use std::collections::HashMap;                         #1
 
struct City {
    name: String,
    population: HashMap<i32, i32>,                     #2
}
 
fn main() {
 
    let mut tallinn = City {
        name: "Tallinn".to_string(),
        population: HashMap::new(),                    #3
    };
 
    tallinn.population.insert(2020, 437_619);          #4
    tallinn.population.insert(1372, 3_250);
    tallinn.population.insert(1851, 24_000);           #5
 
    for (year, population) in tallinn.population {     #6
        println!("In {year}, Tallinn had a population of {population}.");
    }
}

Compare unordered HashMap iteration with the BTreeMap version by replacing the collection type and observing the output order. section 6.1.1

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines ordered iteration and demonstrates construction, insertion, and traversal, but defers the collection’s internal implementation.
Examples
Demonstrates a city population map keyed by years and prints entries in ascending key order.
What it assumes
Assumes basic Rust structs, loops, collections, and method calls while introducing ordered-map behavior through a HashMap substitution.
What you can do after
Apply BTreeMap by creating one, inserting key-value pairs, and iterating over entries in key order.
How it connects
Connects BTreeMap with HashMap, key-value pairs, insertion, and iteration.

Also explained in

Compare how 2 books explain BTreeMap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.