Combine HashMap keys. Consider a Rust program that has 2 HashMaps, and we want to combine the keys from both into a third collection. We can remove duplicates from the final vector.
Rust method notes. We can place the keys from both HashMaps into an empty vector, and then perform duplicate removal. This reliably gets the union of keys.
Example program. To start, we create 2 HashMaps. The types of the keys and values do not matter, but we should have the same key types for each HashMap.
Info Each HashMap here has string keys. We create an empty str vector, and push all the keys from each HashMap into it.
Detail In Rust we can eliminate duplicates from a vector by calling sort() and then dedup().
use std::collections::HashMap;
fn main() {
// First HashMap.
let mut values1 = HashMap::new();
values1.insert("cat", 1);
values1.insert("dog", 2);
// Second HashMap.
let mut values2 = HashMap::new();
values2.insert("cat", 3);
values2.insert("bird", 4);
// Get keys from both HashMaps.// ... Place in single vector.
let mut vector: Vec<&str> = vec![];
for k in values1.keys() {
vector.push(k);
}
for k in values2.keys() {
vector.push(k);
}
// Sort and dedup, removing all duplicate keys.
vector.sort();
vector.dedup();
println!("{:?}", vector);
}["bird", "cat", "dog"]
Another approach. It would be possible to place all the keys() from the first 2 HashMaps into a third HashMap. Then the keys() of that HashMap would be a combined key list.
A summary. Getting a merged list of keys from 2 HashMaps is useful in many Rust programs. Other approaches are possible, but this code is simple and effective.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.