A BTreeMap is Rust’s ordered collection of key-value pairs. Choose it when key order is useful: iterating over the map visits entries in order, and range queries select a subset by key. section 7.7.10 section 7.7.9
Listing 7.20 Demonstrating range queries and ordered iteration of BTreeMap
1 use std::collections::BTreeMap;
2
3 fn main() {
4 let mut voc = BTreeMap::new();
5
6 voc.insert(3_697_915, "Amsterdam");
7 voc.insert(1_300_405, "Middelburg");
8 voc.insert( 540_000, "Enkhuizen");
9 voc.insert( 469_400, "Delft");
10 voc.insert( 266_868, "Hoorn");
11 voc.insert( 173_000, "Rotterdam");
12
13 for (guilders, kamer) in &voc {
14 println!("{} invested {}", kamer, guilders); #1
15 }
16
17 print!("smaller chambers: ");
18 for (_guilders, kamer) in voc.range(0..500_000) { #2
19 print!("{} ", kamer); #1
20 }
21 println!("");
22 }
The investments are inserted in no particular order. Iterating over the map prints them by ascending investment amount; `range(0..500_000)` selects only amounts below 500,000. section 7.7.10
When choosing a map:
- Start with HashMap when you only need to associate keys with values. section 7.7.10
- Use BTreeMap when keys have a natural order and your program benefits from that order or needs a range query. section 7.7.10 section 7.7.9
Selecting smaller investments
With investment amounts as keys and chamber names as values, `voc.range(0..500_000)` yields Rotterdam, Hoorn, and Delft. Iterating over the entire map prints all six chambers from the smallest investment to the largest. section 7.7.10

