← 中文资源

简体中文版本

按值排序 map 条目

HashMap 顺序不固定:into_iter 把条目收进 Vec,sort_by_key 按值排序,Reverse 包一层即得点击数从高到低的报表,稳定排序保留同值原序。

阅读英文原文

实现说明

按值排序 map 条目的核心是函数 main。 for path in ["/orders", "/health", "/orders", "/billing", "/orders", "/health"] 反复执行,循环体之外没有别的重复。

使用要点

  • 跑完文件,输出里会留下标记——by count:、top first:。

常见问题

运行「按值排序 map 条目」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 by count:、top first: 标签标明各步骤。

核心语句

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

代码示例

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:?}");
}