Sort HashMap Entries By Count

Drain a HashMap into a Vec of pairs and sort_by_key on the count, using Reverse for top-first reports since map order itself is unspecified.

RustData Integrity

Code

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

fn main() {
    let mut hits: HashMap<&str, u32> = HashMap::new();
    for path in ["/orders", "/health", "/orders", "/billing", "/orders", "/health"] {
        *hits.entry(path).or_insert(0) += 1;
    }

    // HashMap 顺序不固定:先收进 Vec 再按 value(计数)排序
    let mut rows: Vec<(&str, u32)> = hits.into_iter().collect();
    rows.sort_by_key(|&(_path, count)| count);
    println!("by count: {rows:?}");

    // Reverse 包一层即反向:点击最多的路径排最前
    rows.sort_by_key(|&(_path, count)| std::cmp::Reverse(count));
    println!("top first: {rows:?}");
}

The flow of the file

All of the logic is contained in the function main.

A single loop drives the file — for path in ["/orders", "/health", "/orders", "/billing", "/orders", "/health"].

Points of care

  • The import surface (if any) is all standard library, all versioned with the language itself.

Applying it

The entry-point signature is fn main()

Output lines are prefixed (by count:, top first:), so every step’s outcome shows up in the output.

Statements that matter

let mut rows: Vec<(&str, u32)> = hits.into_iter().collect();

Interactive Tools for This Topic

FAQ

What does Sort HashMap Entries By Count print when run?
Run it as a complete program — the output lines carry labels such as `by count:`, `top first:`.