// Create an Apex class to find duplicate Contacts by email.
public class DuplicateContactFinder {
// Method to find duplicate contacts by email
public List<Contact> findDuplicateContacts() {
List<Contact> duplicateContacts = new List<Contact>();
// Query for contacts with the same email
List<Contact> contactsWithDuplicates = [SELECT Id, Email FROM Contact GROUP BY Email HAVING COUNT(Id) > 1];
// Loop through the results and add them to the list of duplicates
for (Contact contact : contactsWithDuplicates) {
duplicateContacts.addAll([SELECT Id, FirstName, LastName, Email FROM Contact WHERE Email = :contact.Email]);
}
return duplicateContacts;
}
}
Mastering Salesforce Apex: A 30-Day Challenge to Ace Apex Coding Interviews
Here’s how the code works:
The DuplicateContactFinder class contains a single method, findDuplicateContacts, which returns a list of duplicate contacts.
Inside the method, it first queries the Contact records in the database, grouping them by their email address (GROUP BY Email) and selecting those with more than one occurrence (HAVING COUNT(Id) > 1).
It then iterates through the results and queries for the full details of each contact with the same email address. These contacts are added to the duplicateContacts list.
To use this class, you can create an instance of DuplicateContactFinder and call the findDuplicateContacts method. For example:
DuplicateContactFinder duplicateFinder = new DuplicateContactFinder();
List<Contact> duplicates = duplicateFinder.findDuplicateContacts();
// Now you can work with the list of duplicate contacts
for (Contact duplicate : duplicates) {
System.debug(‘Duplicate Contact: ‘ + duplicate.FirstName + ‘ ‘ + duplicate.LastName + ‘ (‘ + duplicate.Email + ‘)’);
}