liveBook · Manning

BTreeMap

As explained in Rust in Action: Systems programming concepts and techniques

A BTreeMap is a Rust ordered map that stores key-value pairs in a B-tree and supports ordered traversal.

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

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Demonstrates construction, insertion, ordered iteration, and range querying without explaining B-tree internals.
Examples
Shows six investments keyed by amount, printing them in order and selecting amounts below 500,000.
What it assumes
Defines key-value collections and distinguishes Rust’s map implementations before comparing when to use them.
What you can do after
Apply it via std::collections::BTreeMap to iterate in key order and select entries with range.
How it connects
Contrasts BTreeMap with HashMap as implementations of key-value collections and connects ordering to range queries.

Also explained in

Compare how 2 books explain BTreeMap →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.