Summary - Collections
- Rust course
- Intermediate
- Lesson 59/115
- 5 min
Combine HashMap and the Entry API to build a word counter.
Collections summary
HashMap: fast key-value, unordered. BTreeMap: sorted, range queries. HashSet/BTreeSet: unique values and set operations. With the entry API, "insert if missing, update if present" happens in one lookup: or_insert, or_default, and_modify. Iteration uses &, &mut or ownership; the output of unordered structures should be sorted before printing.
Grouping
BTreeMap and or_default together give a sorted grouping:
let mut gruplar: BTreeMap<char, Vec<&str>> = BTreeMap::new();
for k in "elma armut erik ayva kiraz".split_whitespace() {
let ilk = k.chars().next().unwrap();
gruplar.entry(ilk).or_default().push(k);
}
for (h, liste) in &gruplar {
println!("{h}: {}", liste.join(", "));
}Practice Group by first letter
Group the words of "elma armut erik ayva kiraz" by first letter in a BTreeMap<char, Vec<&str>> (or_default). Print each group as letter: word, word on separate lines.
Starter code
use std::collections::BTreeMap;
fn main() {
// buraya yaz
}Sample solution
use std::collections::BTreeMap;
fn main() {
let mut gruplar: BTreeMap<char, Vec<&str>> = BTreeMap::new();
for k in "elma armut erik ayva kiraz".split_whitespace() {
let ilk = k.chars().next().unwrap();
gruplar.entry(ilk).or_default().push(k);
}
for (h, liste) in &gruplar {
println!("{}: {}", h, liste.join(", "));
}
}Expected output
a: armut, ayva e: elma, erik k: kiraz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which value type best fits grouping words by first letter in a map?
- Vec<&str> Correct answer
- &str
- usize
- bool
Explanation: Several words fall under each key; the entry(..).or_default().push(k) pattern builds this naturally.
2 Start with the default
gruplar.entry(ilk).____().push(k);
gruplar.entry(ilk).or_default().push(k);
Explanation: or_default puts an empty Vec if missing.
3 Group summary
| Term | Meaning |
|---|---|
HashMap |
Fast, unordered |
BTreeMap |
Sorted keys |
HashSet |
Unique values |
entry |
Update in one lookup |