Skip to content

Instantly share code, notes, and snippets.

@NickyMeuleman
Created July 8, 2021 15:17
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NickyMeuleman/94eec02fdd5c3d3df937e5428b1d1f5f to your computer and use it in GitHub Desktop.
Save NickyMeuleman/94eec02fdd5c3d3df937e5428b1d1f5f to your computer and use it in GitHub Desktop.
Rust .collect() an iterator into a HashMap
use std::collections::{HashMap, HashSet};
fn count_occurrences(message: &str) -> HashMap<char, usize> {
let unique: HashSet<char> = message.chars().collect();
unique
.iter()
.map(|&c| (c, message.matches(c).count()))
.collect()
}
// count_occurrences("aabcddd")
// {
// 'd': 3,
// 'b': 1,
// 'c': 1,
// 'a': 2,
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment