Rust Ordered Maps & Sets
Quick answer
Choose BTreeMap or BTreeSet when traversal in key order or range queries matter. Unlike hash-based collections, their iteration follows the ordering of keys.
Ordering and ranges
Keys must implement Ord, a total ordering contract introduced in the traits chapter. The map stores key-value pairs; the set stores distinct values. A range like 2..=4 selects keys from two through four, inclusive. Tree ordering trades hashing for ordered comparisons.
use std::collections::BTreeMap;fn main() { let items = BTreeMap::from([("tea", 2), ("bread", 5)]); for (name, count) in &items { println!("{name}: {count}"); }}Expected stdout (not executed):
bread: 5tea: 2Keys appear in lexical order.
use std::collections::BTreeSet;fn main() { let ids = BTreeSet::from([8, 2, 4, 1]); for id in ids.range(2..=4) { println!("{id}"); }}Expected stdout (not executed):
24Only present keys in the requested interval appear.
Common mistake
Sorted key order is not insertion order and is not locale-aware sorting for text.
Try it yourself
Create a map of three numbered appointments and print only appointments in a given inclusive range.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Ordered maps and sets — practice quiz
Choose one answer per question, then review the explanation.
A BTreeSet receives 8, 2, 5. What is its normal iteration order?
Which keys are included by `map.range(2..=4)` for keys 1, 2, 4, 5?
What does inserting an equal key into BTreeMap do?