Home
Rust
HashMap Combine Keys
This page was last reviewed on May 29, 2021.
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.
Vec dedup
HashMap
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
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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on May 29, 2021 (new).
Home
Changes
© 2007-2024 Sam Allen.