You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rust数组转HashMap更简洁写法:保留键对应最大值

Rust 实现按键保留最大值的HashMap构建

以下代码可将数组中每种颜色对应的最大值存入HashMap:

use std::collections::HashMap;
use std::cmp;

fn main() {
    let array = [
        ("blue", 1),
        ("green", 2),
        ("red", 3),
        ("blue", 4),
        ("green", 1),
        ("red", 2),
    ];
    
    let mut scores = HashMap::new();
    
    // 将键值对数组转换为HashMap
    array
        .into_iter()
        .for_each(|(color, color_count)| {
            // 更新HashMap,保留每个键对应的最大值
            scores
                .entry(color)
                .and_modify(|e| { *e = cmp::max(*e, color_count) })
                .or_insert(color_count);
        });

    for (key, value) in &scores {
        println!("{}: {}", key, value);
    }
    
    println!("The product of the values: {}", scores.values().cloned().fold(1, |res, a| res * a));
}

运行后输出如下:

blue: 4
green: 2
red: 3
The product of the values: 24

我遇到的情况是,需要处理的数组来自另一个map函数,若直接将数组转为HashMap,会保留数组中最后一个条目。请问是否有更简洁的链式写法来实现保留最大值的逻辑?


内容的提问来源于stack exchange,提问作者Winston

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 09:12:05