HashMap Iteration Order Is Unspecified

Observe that HashMap visits entries in an order that can differ per run and per process, then produce stable output by sorting keys before iterating.

RustData Integrity

Code

rustsnippet
27 lines
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("ada", 91);
    scores.insert("linus", 87);
    scores.insert("grace", 95);

    // HashMap 迭代顺序未指定:每次运行可能不同(随机种子防哈希碰撞攻击)
    for (name, score) in &scores {
        println!("raw: {name}={score}");
    }

    // 报表、快照测试需要稳定输出:先按键排序再迭代
    let mut names: Vec<_> = scores.keys().collect();
    names.sort();
    for name in names {
        println!("sorted: {name}={}", scores[name]);
    }

    // 按值排序(降序)时用 Vec 排序键值对
    let mut ranked: Vec<_> = scores.iter().collect();
    ranked.sort_by(|a, b| b.1.cmp(a.1));
    for (i, (name, score)) in ranked.iter().enumerate() {
        println!("rank {}: {} ({})", i + 1, name, score);
    }
}

What the code does

HashMap Iteration Order Is Unspecified reduces to the function main.

Iteration happens inside for (name, score) in &scores — everything outside it runs once.

Applying it

Running the file prints labeled results such as raw:, sorted:, rank — each operation’s effect is visible in the output.

Statements that matter

let mut ranked: Vec<_> = scores.iter().collect();
for (i, (name, score)) in ranked.iter().enumerate() {
println!("rank {}: {} ({})", i + 1, name, score);
}
let mut names: Vec<_> = scores.keys().collect();

Interactive Tools for This Topic

FAQ

What does HashMap Iteration Order Is Unspecified print when run?
Running the file directly is enough — expect labeled output lines such as `raw:`, `sorted:`, `rank`.