Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TheRealBenSmith/b598f9081aef0d5a1678 to your computer and use it in GitHub Desktop.
Save TheRealBenSmith/b598f9081aef0d5a1678 to your computer and use it in GitHub Desktop.
Simple Lead Deduping from the Salesforce Developer Console
//Provide the id of the default user for new leads or the default queue for new leads so we can make sure we only get rid of these leads
String ownerId = '00Go0000001iGfU';
//Start with a list of all leads with email addresses that are not converted (and in our case not currently with a status of Duplicate)
//Also pull owner ID so we can use that to determine if the leads are owned by the new lead queue (or not)
List<Lead> newleads = [select id, email, ownerid from Lead where email != null and isConverted = false and Status != 'Duplicate'];
//Create a map, indexed by email, that will store lists of leads with the same email address
Map<String, List<Lead>> leadsByEmail = new Map<String, List<Lead>>();
//Put the leads into lists by email in the map
for (Lead l : newleads) {
List<Lead> emailLeads = new List<Lead>();
if (leadsByEmail.containsKey(l.email)) {
emailLeads = leadsByEmail.get(l.email);
}
emailLeads.add(l);
leadsByEmail.put(l.email, emailLeads);
}
//Create a list to store the leads we want to deal with as duplicates
List<Lead> leadsToHandle = new List<Lead>();
//Go through each list of leads in the map
for (String email : leadsByEmail.keySet()) {
//If there's more than one item in the list we need to do something
if (leadsByEmail.get(email).size() > 1) {
//Check to see how many leads in the lists are not owned by the default user
Integer ownedCount = 0;
Integer listSize = leadsByEmail.get(email).size();
for (Lead l : leadsByEmail.get(email)){
if (!String.valueOf(l.ownerid).startsWith(ownerId)) {
ownedCount++;
}
}
//If only one lead is not owned by the default user, then we can assume that the others are duplicates and deal with them accordingly
if (ownedCount == 1) {
for (Lead l : leadsByEmail.get(email)){
if (String.valueOf(l.ownerid).startsWith(ownerId)) {
leadsToHandle.add(l);
}
}
}
}
}
//Send the size to the debug log just for a sanity check
system.debug(leadsToHandle.size());
// You can debug out the leads or you could go through the list and update their status, below we simply delete them.
//delete leadsToHandle;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment