Rust Combine HashMap KeysMerge together the keys from 2 HashMaps by using a vector and then calling sort and dedup.
dot net perls
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.
dedup Vector
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.
String Array
Dedup In Rust we can eliminate duplicates from a vector by calling sort() and then dedup().
Rust program that combines keys from 2 HashMaps
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.
© 2007-2021 sam allen. see site info on the changelog