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
相关产品推荐
相关产品推荐

