Group records in a Map<String, List<Contact>>
Apex basics · Beginner · 12 min · Runs in your Salesforce Developer org · Free
Write `countInTitleGroup(List<Contact> contacts, String targetTitle)` that groups Contacts by `Title` into a `Map<String, List<Contact>>` and returns how many fall under the target Title. Create the inner list the first time you see a Title. Return `0` when the Title is not in the map.
Lesson
Why this matters
Grouping records by a shared field is one of the most useful Apex patterns: Contacts by Title, Opportunities by StageName, Cases by Owner. A Map<String, List<Contact>> keeps every row from each group in order, so you can read a whole group with one get.
The smallest working example
Map<String, List<Contact>> byTitle = new Map<String, List<Contact>>();
for (Contact row : contacts) {
if (!byTitle.containsKey(row.Title)) {
byTitle.put(row.Title, new List<Contact>());
}
byTitle.get(row.Title).add(row);
}
After the loop, byTitle.get('Manager') is the list of every Contact whose Title is 'Manager'.
Name the parts
- **
Map<String, List<Contact>>** holds a list of Contacts per Title. - **
containsKey** checks whether the Map already has a bucket for that Title. - **
new List<Contact>()** creates the empty inner list the first time you see a Title. - **
byTitle.get(title).add(row)** appends the Contact to the right bucket.
A common wrong version
for (Contact row : contacts) {
byTitle.get(row.Title).add(row);
}
The first time you see a Title, byTitle.get(title) returns null, and null.add(...) throws a NullPointerException. You must create the inner list before you append to it.
The fix
Guard with containsKey and create a fresh new List<Contact>() the first time a Title appears. After the loop, call byTitle.get(targetTitle); if it is null, return 0, otherwise return .size().
Now you try
Finish countInTitleGroup so it builds the map and returns the group's size.
Learn more
The challenge
Write countInTitleGroup(List<Contact> contacts, String targetTitle) that groups Contacts by Title and returns how many fall under the target Title.
Examples:
- two Managers plus a Dev with
targetTitle = 'Manager'→2 - one Dev with
targetTitle = 'Manager'→0 - an empty list with any target →
0
Requirements:
countInTitleGroupwith two Managers and a Dev, targetManager, should be2.countInTitleGroupwith one Dev and targetManagershould be0.countInTitleGroupwith an empty list and targetManagershould be0.countInTitleGroupwith one matching Contact should be1.countInTitleGroupwith three Devs and targetDevshould be3.countInTitleGroupwith one Analyst and targetDirectorshould be0.
Starter code
Integer countInTitleGroup(List<Contact> contacts, String targetTitle) {
return null;
}
Related drills
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Find the compile error · Convert text to Integer, safely ›