Rust HashMap Tutorial: String Keys, Integer Vectors
Rust Arrays: Exercise-9 with Solution
Write a Rust program that creates a HashMap where the keys are strings and the values are vectors of integers, then add elements to the vectors based on certain conditions.
Sample Solution:
Rust Code:
use std::collections::HashMap; // Import the HashMap type from the standard library
fn main() {
// Create an empty HashMap where the keys are strings and the values are vectors of integers
let mut my_hashmap: HashMap<String, Vec<i32>> = HashMap::new(); // Key: String, Value: Vec<i32>
// Define some sample data
let data = vec![
("even", 2),
("odd", 3),
("even", 4),
("odd", 5),
("even", 6),
("odd", 7),
];
// Iterate over the sample data
for (key, value) in data {
// Check if the key exists in the HashMap
if let Some(vec) = my_hashmap.get_mut(key) {
// If the key exists, add the value to the corresponding vector
vec.push(value);
} else {
// If the key does not exist, create a new vector with the value and insert it into the HashMap
my_hashmap.insert(key.to_string(), vec![value]);
}
}
// Print the HashMap containing keys as strings and values as vectors of integers
println!("HashMap: {:?}", my_hashmap);
}
Output:
HashMap: {"even": [2, 4, 6], "odd": [3, 5, 7]}
Explanation:
Here is a brief explanation of the above Rust code:
- use std::collections::HashMap;: Imports the "HashMap" type from the standard library, allowing us to use HashMaps in our code.
- fn main() { ... }: Defines the main function, which is the entry point of the Rust program.
- let mut my_hashmap: HashMap<String, Vec<i32>> = HashMap::new();: Creates an empty HashMap named 'my_hashmap' where the keys are strings (String) and the values are vectors of integers (Vec<i32>).
- let data = vec![ ... ];: Defines some sample data as a vector of tuples, where each tuple contains a key (string) and a value (integer).
- for (key, value) in data { ... }: Starts a loop to iterate over each tuple in the sample data, extracting the key and value from each tuple.
- if let Some(vec) = my_hashmap.get_mut(key) { ... }: Checks if the key exists in the HashMap. If the key exists, it returns a mutable reference to the corresponding vector (vec) using the 'get_mut()' method.
- vec.push(value);: Adds the value to the corresponding vector if the key exists in the HashMap.
- } else { ... }: Handles the case where the key does not exist in the HashMap.
- my_hashmap.insert(key.to_string(), vec![value]);: Creates a new vector containing the value and inserts it into the HashMap with the key converted to a string (key.to_string()).
- println!("HashMap: {:?}", my_hashmap);: Prints the HashMap containing keys as strings and values as vectors of integers after processing all the sample data.
Rust Code Editor:
Previous: Rust HashMap Merging & Printing.
Next: Rust Character Frequency Counter.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/rust/collections_and_data_structures/rust-hashmaps-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics