Count Leads by Rating with a Map
Write Apex · Beginner · 15 min · Runs in your Salesforce Developer org · Free
Scenario. A sales manager wants to know how many Leads are Hot, Warm or Cold, and how many nobody has rated yet.
Write a method that counts Leads per Rating in a Map<String, Integer>, then loop over its keys to print each count.
What you will learn
A Map<String, Integer> can keep a running count for each key. containsKey checks for a key, get reads its value, and put saves a new one.
if (counts.containsKey(key)) {
counts.put(key, counts.get(key) + 1);
} else {
counts.put(key, 1);
}
Loop over every key with for (String key : counts.keySet()).
Gotcha. get on a key the Map doesn't have returns null, and null + 1 throws an error.
The task
Write a method countByRating(List<Lead> leads) that returns how many Leads have each Rating.
Examples:
- the starter's Leads (Hot, Warm, Hot and one with no Rating) →
get('Hot')is2andget('None')is1 - a Rating no Lead has, like
get('Cold')for the same Leads →null - a loop over the keys prints
Hot: 2,Warm: 1andNone: 1
Requirements:
- Loop over the Leads and count each
Ratingin aMap<String, Integer>. Count a Lead with no Rating underNone. - Use
containsKeyto start a new Rating at 1, andgetplusputto add 1 to a Rating you have seen. - Return the Map, and keep the method's name and input. The grader also calls it with other Leads, some of them hidden.
- Loop over
counts.keySet()and print each Rating and its count, such asHot:,Warm:andNone:.
Starter code
Map<String, Integer> countByRating(List<Lead> leads) {
return null;
}
List<Lead> leads = new List<Lead>{
new Lead(LastName = 'Ito', Company = 'Acme', Rating = 'Hot'),
new Lead(LastName = 'Park', Company = 'Globex', Rating = 'Warm'),
new Lead(LastName = 'Diaz', Company = 'Initech', Rating = 'Hot'),
new Lead(LastName = 'Chen', Company = 'Umbrella')
};
Map<String, Integer> counts = countByRating(leads);
When it passes
Your method returns one count per Rating, counts Leads with no Rating under None, and leaves out Ratings no Lead has.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.