RRust By Example
intermediateCollections

BTreeMap Range Queries

Query ranges in sorted maps with BTreeMap.

BTreeMap Range Queries

Query ranges in sorted maps with BTreeMap.

Difficulty

Intermediate

Code

rust
use std::collections::BTreeMap;

fn main() {
    let mut scores: BTreeMap<&str, i32> = BTreeMap::new();
    scores.insert("Alice", 85);
    scores.insert("Bob", 92);
    scores.insert("Charlie", 78);
    scores.insert("Diana", 95);
    scores.insert("Eve", 88);

    // range: all entries with keys between "B" and "D"
    println!("B-D range:");
    for (name, score) in scores.range("B".."D") {
        println!("  {}: {}", name, score);
    }

    // range_inclusive
    println!("A-C inclusive:");
    for (name, score) in scores.range("A"..="C") {
        println!("  {}: {}", name, score);
    }

    // first and last
    println!("first: {:?}", scores.iter().next());
    println!("last: {:?}", scores.iter().next_back());
}

Explanation

BTreeMap supports range queries for sorted data.

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