Created
July 8, 2021 15:17
-
-
Save NickyMeuleman/94eec02fdd5c3d3df937e5428b1d1f5f to your computer and use it in GitHub Desktop.
Rust .collect() an iterator into a HashMap
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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