Search code examples
rustrayon

How to iterate through a HashMap in parallel in Rust?


I have a HashMap and want to iterate through its values in parallel using rayon. I cannot consume it and it is not feasible to first create a Vec from the values.

Does anyone have an idea on how to do this?


Solution

  • Does anyone have an idea on how to do this?

    Rayon implements IntoParallelIterator for &HashMap.

    So you can just call par_iter on the hashmap with rayon's prelude imported and it'll work: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=e710e23bcc99bd09ce4fab5ba7544604

    use std::collections::HashMap;
    use rayon::prelude::*;
    
    fn main() {
        let h = HashMap::from([
            ("foo", 1),
            ("bar", 2),
            ("baz", 3),
            ("qux", 4),
            ("quux", 5),
        ]);
        thing(&h);
    }
    
    fn thing(m: &HashMap<&str, usize>) {
        let v: usize = m.par_iter()
            .map(|(_, v)| *v)
            .sum();
        println!("{}", v);
    }