Rust Building a HashMap
Building a HashMap from two lists pairs each item in one list with the item at the same position in the other list. Rust zips the two lists into pairs, and collect() then gathers the pairs into a HashMap.
Pair two lists with zip
zip walks two lists together and pairs them by position: first with first, second with second:
let teams = vec!["Blue", "Yellow"];
let pairs = teams.into_iter().zip(vec![10, 50]);Collect the pairs into a HashMap
collect() gathers the pairs into the collection named in the type note — here a HashMap:
let teams = vec!["Blue", "Yellow"];
let points = vec![10, 50];
let scores: HashMap<&str, i32> = teams.into_iter().zip(points.into_iter()).collect();
println!("pairs = {}", scores.len());Ask whether a key exists
contains_key answers true or false, without handing you the value:
let mut scores = HashMap::new();
scores.insert("Blue", 10);
println!("has Blue = {} has Red = {}", scores.contains_key("Blue"), scores.contains_key("Red"));Group records by a key
The first "red" starts an empty Vec. Every name after that joins its team's group.
let signups = [("red", "Ana"), ("blue", "Bo"), ("red", "Cy")];
let mut by_team: HashMap<&str, Vec<&str>> = HashMap::new();
for (team, name) in signups {
by_team.entry(team).or_default().push(name);
}
println!("red team = {:?}", by_team["red"]);Example
use std::collections::HashMap;
fn main() {
let teams = vec![String::from("Blue"), String::from("Yellow")];
let points = vec![10, 50];
let scores: HashMap<String, i32> = teams.into_iter().zip(points.into_iter()).collect();
let blue = scores.get("Blue").copied().unwrap_or(0);
println!("Blue = {} teams = {}", blue, scores.len());
println!("has Yellow = {}", scores.contains_key("Yellow"));
}Key points
- Two lined-up lists become one map: zip pairs them, and collect builds the HashMap.
- The type note names the key and value types, and collect() builds exactly that map.
In this example, teams and points are two Vecs lined up by position: Blue with 10, Yellow with 50. into_iter() hands the values over, zip pairs them, and collect() builds the HashMap named in the type note. get("Blue") gives a reference to 10. copied() turns it into a plain number. unwrap_or(0) would give 0 if the key were missing. len() counts 2 pairs, and contains_key confirms Yellow is there.
Note
collect() also gathers text pieces into a Vec.
The type note tells collect() which collection to build this time.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
What does zip do to two iterators?