RRust By Example
intermediateCollections

BTreeMap

Sorted key-value map with B-tree implementation.

BTreeMap

Sorted key-value map with B-tree implementation.

Difficulty

Intermediate

Code

rust
use std::collections::BTreeMap;

fn main() {
    let mut map = BTreeMap::new();
    map.insert("three", 3);
    map.insert("one", 1);
    map.insert("two", 2);

    // keys are always sorted
    for (key, value) in &map {
        println!("{}: {}", key, value);
    }
}

Explanation

BTreeMap keeps keys sorted.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the collections category to build a complete understanding of this topic.

More Collections Examples