ApexSensei

Drills › Write Apex

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') is 2 and get('None') is 1
  • a Rating no Lead has, like get('Cold') for the same Leads → null
  • a loop over the keys prints Hot: 2, Warm: 1 and None: 1

Requirements:

  1. Loop over the Leads and count each Rating in a Map<String, Integer>. Count a Lead with no Rating under None.
  2. Use containsKey to start a new Rating at 1, and get plus put to add 1 to a Rating you have seen.
  3. Return the Map, and keep the method's name and input. The grader also calls it with other Leads, some of them hidden.
  4. Loop over counts.keySet() and print each Rating and its count, such as Hot:, Warm: and None:.

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.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Remove duplicate emails with a Set