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

