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.