Merge Maps Summing Collisions
Consume the second map with into_iter and add each value into entry, so colliding keys sum instead of replace and ownership moves without cloning.
Code
use std::collections::HashMap;
fn main() {
let first: HashMap<String, u32> = [
("orders", 120),
("billing", 45),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
let second: HashMap<String, u32> = [
("orders", 30),
("auth", 12),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v))
.collect();
// second 被 into_iter 消费:键值对所有权移入 first,同名键的值相加
let mut merged = first;
for (key, value) in second {
*merged.entry(key).or_insert(0) += value;
}
// HashMap 顺序不固定:排序后再输出保证稳定
let mut rows: Vec<(String, u32)> = merged.into_iter().collect();
rows.sort();
for (key, total) in rows {
println!("{key}: {total}");
}
}The mechanics
Merge Maps Summing Collisions comes down to the function main.
The cycling part of this snippet is for (key, value) in second.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Using it
Entry signature: fn main()
Key statements
let mut rows: Vec<(String, u32)> = merged.into_iter().collect();
rows.sort();
.map(|(k, v)| (k.to_string(), v))
.collect();
Interactive Tools for This Topic
FAQ
- How do you run Merge Maps Summing Collisions?
- Nothing to install first — run the file and the program does the rest.
Report a problem with this exampleOpens a pre-filled issue on GitHub.