How to remove duplicates from list in Salesforce?

How to remove duplicates from list in Salesforce?

Create a map instead of list and finally insert or update the map values. Check the following code to remove duplicates from list in Salesforce.

Sample Code:

Map < Id, Account > mapAccount = new Map < Id, Account >();
List < Account > listAccount = new List < Account >();
Account objAccount = [ 
    SELECT Id, Name
    FROM Account
    WHERE Name = 'InfallibleTechie'
    LIMIT 1
];   
listAccount.add( objAccount );
listAccount.add( objAccount );
listAccount.add( objAccount );
System.debug( 'listAccount size is ' + listAccount.size() );

for ( Account acc : listAccount ) {
    
    mapAccount.put( acc.Id, acc );
    
}

System.debug( 'mapAccount size is ' + mapAccount.size() );

Output:

Leave a Reply