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.
It's dubious if it's more elegant, but fold
ing 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
})
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With