Counting and Grouping
Common map-based patterns.
Counting and Grouping is a free Learn Rust Coding lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn Rust Coding learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Counting Things
A very common task is counting how many times each value appears in a collection.
A HashMap from value to count is the natural tool. The key is the item, the value is its tally.
The Counting Pattern
For each item, look up its slot, default it to zero, and add one.
The entry API makes this a single, clear line. This pattern works for any countable item.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for n in [1, 1, 2, 3, 3, 3] {
*counts.entry(n).or_insert(0) += 1;
}
println!("threes: {}", counts[&3]);
}Counting Characters
Strings are made of characters, so you can count letter frequency the same way.
Iterate with chars() and tally each one into the map.
use std::collections::HashMap;
fn main() {
let mut freq = HashMap::new();
for c in "banana".chars() {
*freq.entry(c).or_insert(0) += 1;
}
println!("a: {}, n: {}", freq[&'a'], freq[&'n']);
}Counting Words
To count words, split a sentence on whitespace with split_whitespace.
Each piece becomes a key. This is the basis of a simple word-frequency analyzer.
use std::collections::HashMap;
fn main() {
let text = "go go stop go";
let mut counts = HashMap::new();
for w in text.split_whitespace() {
*counts.entry(w).or_insert(0) += 1;
}
println!("go: {}", counts["go"]);
}Finding the Maximum Count
Once you have counts, find the most frequent item by iterating and tracking the highest value.
You can compare each entry's count against the best seen so far.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for c in "aabbbc".chars() {
*counts.entry(c).or_insert(0) += 1;
}
let top = counts.iter().max_by_key(|(_, &v)| v).unwrap();
println!("most common: {}", top.0);
}Grouping Items
Grouping puts items into buckets that share a property.
Use a HashMap from group key to a Vec of members. The entry API defaults to an empty vector on first use.
use std::collections::HashMap;
fn main() {
let mut groups: HashMap<bool, Vec<i32>> = HashMap::new();
for n in 1..=6 {
groups.entry(n % 2 == 0).or_default().push(n);
}
println!("evens: {:?}", groups[&true]);
}Grouping by First Letter
A natural grouping key is the first character of a word.
Extract it, then push each word into the matching bucket.
use std::collections::HashMap;
fn main() {
let words = ["apple", "avocado", "banana"];
let mut by_letter: HashMap<char, Vec<&str>> = HashMap::new();
for w in words {
let first = w.chars().next().unwrap();
by_letter.entry(first).or_default().push(w);
}
println!("a-words: {}", by_letter[&'a'].len());
}Grouping by Length
You can group by any computed property, such as the length of each word.
The key is a number here, and each bucket collects words of that length.
use std::collections::HashMap;
fn main() {
let words = ["hi", "yo", "hey", "hello"];
let mut by_len: HashMap<usize, Vec<&str>> = HashMap::new();
for w in words {
by_len.entry(w.len()).or_default().push(w);
}
println!("len 2: {}", by_len[&2].len());
}Counting Unique Items
To count distinct values, combine a set with a map. Or simply collect into a HashSet and read its length.
This tells you how many different items appear, ignoring repeats.
use std::collections::HashSet;
fn main() {
let visits = ["sam", "mia", "sam", "leo", "mia"];
let unique: HashSet<&str> = visits.iter().copied().collect();
println!("unique visitors: {}", unique.len());
}Reporting Results
After counting or grouping, loop over the map to print a report.
Remember the order is unspecified; sort the keys first if you need stable output.
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for c in "abca".chars() {
*counts.entry(c).or_insert(0) += 1;
}
let mut keys: Vec<_> = counts.keys().collect();
keys.sort();
for k in keys {
println!("{}: {}", k, counts[k]);
}
}Summing Per Group
Instead of collecting members, you can aggregate them, such as summing values per key.
Default the slot to zero and add each item's value, just like counting but with real amounts.
use std::collections::HashMap;
fn main() {
let sales = [("a", 10), ("b", 5), ("a", 3)];
let mut totals: HashMap<&str, i32> = HashMap::new();
for (k, amount) in sales {
*totals.entry(k).or_insert(0) += amount;
}
println!("a total: {}", totals["a"]);
}Quick Check
You want to group words into buckets by their first letter.
Recap
You counted items, characters, and words with the entry pattern, and found the most frequent value.
You grouped items into Vec buckets by letter and length, and counted distinct values with a HashSet.
Frequently asked questions
Is the “Counting and Grouping” lesson free?
Yes — the full text of “Counting and Grouping” is free to read here on the web, and the Learn Rust Coding course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn Rust Coding course, upgrade to CoddyKit PRO.
What will I learn in “Counting and Grouping”?
Common map-based patterns. You practise Learn Rust Coding with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn Rust Coding?
No prior experience is required. Learn Rust Coding on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Counting and Grouping” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn Rust Coding lesson?
Yes. Every Learn Rust Coding lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Building a HashMap
- Entry API and Defaults
- Working with HashSet
- Counting and Grouping