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.
Code
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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.