`BTreeMap`
BTreeMap<K, V> is an ordered map backed by a B-tree. Lookup is O(log n). Iteration is in key order, and you can query ranges of keys.
Detailed Explanation
BTreeMap keeps its keys sorted by Ord. iter walks from smallest key to largest. range(low..=high) walks a slice of that order without scanning the rest. That is the reason this type exists. A HashMap cannot give you "every session id between A and B" without visiting every entry.
The cost is the log n probe and the poorer cache behaviour of a tree versus a flat hash table. For a few dozen entries you will not care. For a cache of millions of unordered ids, HashMap is faster. For a leaderboard, a time-keyed log, or a map you will pretty-print in tests, BTreeMap is the better default.
Keys need Ord, not Hash. That is why BTreeMap accepts types that are ordered but painful to hash, and why it refuses types that are hashable but only partially ordered (f64 without a total-order wrapper). A newtype that implements Ord on a u64 timestamp is a typical key.
The entry API exists here too: or_insert, or_insert_with, and_modify. split_off splits the tree at a key and returns the right half — a cheap-ish way to carve a range into a new map. first_key_value and last_key_value are O(log n) peeks at the ends.
BTreeMap is deterministic. The same inserts produce the same iteration order on every run, which is why people use it in tests and in serialisation when they do not want a hash seed in the snapshot. It is still not thread-safe.
When you reach for BTreeMap: sorted iteration, range queries, deterministic order. When you reach for HashMap: unordered lookup is the whole problem. When you reach for BTreeSet: you need the keys only.
Code Examples
use std::collections::BTreeMap;
fn main() {
let mut scores = BTreeMap::new();
scores.insert("ada", 10);
scores.insert("al", 7);
scores.insert("grace", 9);
for (name, score) in &scores {
println!("{name} {score}");
}
// prints in key order:
// ada 10
// al 7
// grace 9
let mid: Vec<_> = scores.range("al"..="grace").map(|(k, _)| *k).collect();
println!("{mid:?}"); // prints: ["al", "grace"]
}Common Gotchas
Keys need `Ord`, not `Hash`
`BTreeMap<f64, V>` will not compile. Wrap the float in a type with a total order, or use an integer.
Log n is not free at huge n
A hot cache of millions of unordered keys wants `HashMap`. Do not pick `BTreeMap` only because it feels safer.
Order is a public behaviour
Changing the `Ord` impl of a key type reorders the map. Keep `Ord` consistent with `Eq`.
Range bounds are like slicing
`range(a..b)` excludes `b`. `range(a..=b)` includes it. The same off-by-one as `..` versus `..=`.