HashMap & BTreeMap
HashMap offers fast average lookups. BTreeMap keeps keys sorted for range queries and deterministic iteration.
Search across all documentation pages
HashMap offers fast average lookups. BTreeMap keeps keys sorted for range queries and deterministic iteration.
use std::collections::HashMap;
fn count_words(text: &str) -> HashMap<&str, u32> {
let mut counts = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
counts
}When to reach for this: Frequency tables, indexes, caches - pick BTreeMap when order or range scans matter.
use std::collections::BTreeMap;
fn top3(scores: BTreeMap<&str, i32>) -> Vec<(&str, i32)> {
let mut v: Vec<_> = scores.into_iter().collect();
v.sort_by(|a, b| b.1.cmp(&a.1));
v.truncate(3);
v
}What this demonstrates:
BTreeMap iterates keys in orderVec for custom sort by valueentry API avoids double lookup in counts exampleHashMap needs BuildHasher (default RandomState). BTreeMap needs Ord keys. entry returns OccupiedEntry / VacantEntry.
OrderedFloat or integer key.ahash/fxhash for perf (crates).entry not get+insert separately.map.get("str") for String keys via Borrow.HashMap::with_capacity(n) reduces realloc.| Alternative | Use When | Don't Use When |
|---|---|---|
IndexMap | Insertion order | Std only policy |
DashMap | Concurrent map | Single-threaded |
Vec of pairs | Tiny n | Large lookup tables |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026