How do I collect elements of a vector into a HashMap in Rust? The vector contains…
Private research annotation
Sign in to add a private research label or note.
- User
How do I collect elements of a vector into a HashMap in Rust? The vector contains tuples, the first element of which is the key for the HashMap. The second element should add to a Vec value in the HashMap at the key
- Assistant
You can use a
forloop to iterate over the vector and insert the elements into theHashMap. Here's an example of how you can do this:codeuse std::collections::HashMap; fn collect_into_hashmap(vec: Vec<(i32, i32)>) -> HashMap<i32, Vec<i32>> { let mut map = HashMap::new(); for (k, v) in vec { // If the key doesn't exist in the map, insert a new empty Vec. // Otherwise, get the existing Vec. let mut values = map.entry(k).or_insert(Vec::new()); // Push the value onto the Vec values.push(v); } map } fn main() { let vec = vec![(1, 2), (1, 3), (2, 4)]; let map = collect_into_hashmap(vec); println!("{:?}", map); // Output: {1: [2, 3], 2: [4]} }This will create a
HashMapwith keys of type and values of type . For each element in the input , it will insert the key and value into the . If the key already exists in the , it will get the existing and push the value onto it. If the key doesn't exist, it will insert a new empty and then push the value onto it.