Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a collection of values into a HashMap that counts them?

Tags:

rust

I have a collection of items, with repetitions, and I want to create a HashMap that has the items as keys, and the count of how many times they appear in the original collection.

The specific example I'm working on is a string where I want to count how many times each character appears.

I can do something like this:

fn into_character_map(word: &str) -> HashMap<char, i32> {
    let mut characters = HashMap::new();

    for c in word.chars() {
        let entry = characters.entry(c).or_insert(0);
        *entry += 1;
    }

    characters
}

But I was wondering if there's a more elegant solution. I was thinking of using collect(), but it doesn't maintain state between items, so doesn't seem to support what I need.

This came up as I was writing my solution to the 'Anagram' problem on Exercism.

like image 397
Hershi Avatar asked May 01 '16 20:05

Hershi


1 Answers

It's dubious if it's more elegant, but folding using a HashMap requires fewer lines:

fn into_character_map(word: &str) -> HashMap<char, i32> {
    word.chars().fold(HashMap::new(), |mut acc, c| {
        *acc.entry(c).or_insert(0) += 1;
        acc
    })
}
like image 56
Shepmaster Avatar answered Sep 26 '22 03:09

Shepmaster