HashMap
keysConsider 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.
We can place the keys from both HashMaps
into an empty vector, and then perform duplicate removal. This reliably gets the union of keys.
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
.
HashMap
here has string
keys. We create an empty str
vector, and push all the keys from each HashMap
into it.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"]
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.
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.