function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Michael Hedrick 2Michael Hedrick 2 

Merge Duplicate Records Apex Class Help

Hello All,
A fellow community member assited me with the Apex class below.
This process take leads with the same email address and merges all of the activties on these leads to the oldest lead.
Then the code deletes the remaining Leads.  All of the Leads are marked with a checkbox to indicate that they are a duplicate.
So instead of deleting I want to uncheck the checkbox on the new master Lead.
 In the class is the line of code t.WhoId = masterLead.Id; Assigning the master Lead?
can I add 
t.WhoId = masterLead.Id;
masterLead.checkbox = false;
And this would uncheck the checkbox just on the master lead and leave the checkbox checked on the other duplicate leads?
 
List<Lead> leads = [Select Id, Email, (Select Id, WhoId from Tasks), (Select Id, WhoId from Events) from Lead ORDER BY CreatedDate];

Map<String,List<Lead>> leadsMap = new Map<String,List<Lead>>();

for( Lead l : leads ) {
    if( !leadsMap.containsKey( l.Email ) ) {
        leadsMap.put( l.Email, new List<Lead>() );
    }

    leadsMap.get( l.Email ).add( l );
}

List<Event> eventsToUpdate = new List<Event>();
List<Task> tasksToUpdate = new List<Task>();
List<Lead> leadsToDelete = new List<Lead>();


for( String email : leadsMap.keySet() ) {
    List<Lead> leadsToMerge = leadsMap.get( email );
    if( leadsToMerge.size > 1 ) {
        Lead masterLead = leadsToMerge[0];

        for( Integer i = 1; i < leadsToMerge.size(); i++ ) {
            Lead mergedLead = leadsToMerge[index];
            for( Task t : mergedLead.Tasks ) {
                t.WhoId = masterLead.Id;
                tasksToUpdate.add( t );
            }

            for( Event e : mergedLead.Event ) {
                e.WhoId = masterLead.Id;
                eventsToUpdate.add( e );
            }
            leadsToDelete.add( mergedLead );
        }

    }
}

if( eventsToUpdate.size() > 0 ) update eventsToUpdate;
if( tasksToUpdate.size() > 0 ) update tasksToUpdate;
if( leadsToDelete.size() > 0 ) delete leadsToDelete;

Thanks,
M