I have the following code which finds all the unique values from a hashmap of String to Vec. I cobbled it together (eventually as I was getting various borrow errors along the way), but it looks a mess to me and I'm looking for a more idiomatic way of doing it in rust.
fn main() {
let mut my_map: HashMap<String, Vec<String>> = HashMap::new();
my_map.insert("option1".to_string(), vec![String::from("sarah"), String::from("john")]);
my_map.insert("option2".to_string(), vec![String::from("john"), String::from("mark")]);
let x: Vec<String> = my_map.values().flat_map(|x| x).cloned().collect();
// or use flatten() instead of flat_map(|x| x)
let y: HashSet<&String> = HashSet::from_iter(x.iter());
let mut z = y.iter().collect::<Vec<_>>();
z.sort();
println!("{:?}", z);
}
My idea was to flatmap the values from the map down into a simple vector, and then find the unique values (putting everything into a hashset), then converting back to a vector of strings.
The output is the sorted list of all unique names in the Vectors:
["john", "mark", "sarah"]
What would be a better implementation of this in rust?