Group words by first letter into a HashMap<char, Vec<String>> with entry
Write group_by_first, which puts each word into the list of its first character and keeps the input order inside each list.
Requirements:
- Look the key up once per word through the entry API: no
contains_keyfollowed byinsert. - Skip empty strings. The first character is a
char, so"яблоко"goes under'я'. ["apple", "banana", "avocado"]gives'a'→["apple", "avocado"]and'b'→["banana"].
use std::collections::HashMap;
fn group_by_first(words: &[&str]) -> HashMap<char, Vec<String>> {
// your code here
}Write the implementation.
Do not add extra use lines unless the task says so explicitly.
Per word take w.chars().next(), skipping the None of an empty word, and call map.entry(c).or_default().push(w.to_string()). entry finds or creates the slot in one lookup; or_default inserts an empty Vec, like or_insert_with(Vec::new).
- Writing
contains_key, theninsert, thenget_mut: three lookups whereentryneeds one - Taking the key as
w.as_bytes()[0] as char, which garbles any non-ASCII first letter - Believing
or_insert(Vec::new())is lazy, though its argument is always evaluated
- Why does
entrytake the key by value, and what does that cost withStringkeys? - How would you return the groups sorted by letter, and which map gives that for free?
chars().next() returns the first character as an Option<char>: an empty string has none, and if let skips it. entry(c) looks the key up once and returns its slot in the table — occupied or vacant — and or_default() inserts Vec::new() into a vacant slot and in either case hands back the &mut Vec<String> that receives the push.
use std::collections::HashMap;
fn group_by_first(words: &[&str]) -> HashMap<char, Vec<String>> {
let mut groups: HashMap<char, Vec<String>> = HashMap::new();
for w in words {
if let Some(c) = w.chars().next() {
groups.entry(c).or_default().push(w.to_string());
}
}
groups
}
fn main() {
let groups = group_by_first(&["apple", "banana", "", "avocado", "яблоко"]);
// HashMap iteration order is unspecified, so sort the keys before printing
let mut keys: Vec<&char> = groups.keys().collect();
keys.sort();
for c in keys {
println!("{c} {:?}", groups[c]);
}
// a ["apple", "avocado"]
// b ["banana"]
// я ["яблоко"]
}or_insert_with(Vec::new) does the same thing explicitly. or_insert(Vec::new()), by contrast, evaluates its argument for every word, even when the list already exists; for an empty Vec that is cheap, since it allocates nothing, but for an expensive value the difference shows. The key is a char, not the first byte: w.as_bytes()[0] as char would turn «яблоко» into 'Ñ', the character for byte 209, not «я». If the groups are wanted in alphabetical order, return a BTreeMap<char, Vec<String>> instead — the code is the same, and iteration follows the keys in ascending order.