Count distribution of values - how many times each word appears in a list of words

HashMap entry or_insert test

Given a list of values we would like to know how many times each value appears. The source could be any, but we had them in a vector here. The valus could be also anything, but in this case we have small strings.

examples/count-distribution-of-values/src/main.rs

use std::collections::HashMap;

fn main() {
    let animals = vec![
        "camel", "snake", "camel", "snake", "crab", "snake", "crab", "crab", "crab",
    ];
    let counted = count_in_loop(&animals);
    println!("{:#?}", counted);
}

fn count_in_loop<'a>(words: &'a [&'a str]) -> HashMap<&'a str, u32> {
    let mut counter: HashMap<&str, u32> = HashMap::new();
    for word in words {
        *counter.entry(word).or_insert(0) += 1;
    }
    counter
}


#[test]
fn test_count() {
    let words = vec![
        "camel", "snake", "camel", "snake", "crab", "snake", "crab", "crab", "crab",
    ];
    let expected = HashMap::from([("camel", 2), ("crab", 4), ("snake", 3)]);
    assert_eq!(count_in_loop(&words), expected);
}

Related Pages

HashMap (hash, dictionary, associative array) in Rust

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo