What is the idiomatic way to iterate over a vector of hashmaps using flatten?

Viewed 208

I have the following HashMap:

let mut map = HashMap::new();
map.insert(String::from("one"), 1);
map.insert(String::from("two"), 2);
map.insert(String::from("three"), 3);

To iterate over the HashMap and count the amount of times the value is in 2:

fn count_map(hm: &HashMap<String, i32>, v: i32) -> usize {
    hm.iter().filter(|&(_, b)| *b == v).count()
}

count_map(&map, 2)

If I had an additional HashMap and stored both of those in a vector:

let mut map = HashMap::new();
map.insert(String::from("one"), 1);
map.insert(String::from("two"), 2);
map.insert(String::from("three"), 3);

let mut map2 = HashMap::new();
map2.insert(String::from("two"), 2);
map2.insert(String::from("four"), 4);
map2.insert(String::from("six"), 6);

let vec_map = vec![map, map2];

How would you iterate over vec_map to count the amount of times the value is in 2? I'm aware of flatten but not clear on how to use it.

fn count_hm_two(vec_map: &[HashMap<String, i32>], v: i32) -> usize {
    vec_map.iter()???
}
1 Answers

Iterator::flatten can be used to iterate over nested collections:

fn count_hm_two(hm: &[HashMap<String, i32>], v: i32) -> usize {
    hm.iter().flatten().filter(|&(_, b)| *b == v).count()
}
Related