HashMaps and the Entry API
HashMap stores key value pairs. entry().or_insert makes counting simple. Iteration order is not guaranteed.
Example
use std::collections::HashMap;
let mut count: HashMap<&str, i32> = HashMap::new();
for w in ["go", "is", "go"] { *count.entry(w).or_insert(0) += 1; }
let mut keys: Vec<_> = count.iter().collect();
keys.sort();
println!("{:?}", keys);Result
[("go", 2), ("is", 1)]Exercise
Insert if missing.
map.entry(k).(0)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.