下面的代码将把数组中每种 colored颜色 的最大值转换为哈希图.也是在Rust Playground年.
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();
// Convert array of key value into hashmap
array
.into_iter()
.for_each(|(color, color_count)| {
// Update the 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
我面临的问题是,收集的array
来自另一个map
函数.但我面临的问题是,如果我将数组直接转换为HashMap
,HashMap
将存储最新的条目(数组的底部).我相信有一些更好的方法来链接整个事情,让它看起来更整洁?