Select your language

  • Davide Gammone

            

Davide Gammone.com
How to fix the "Duplicate id in list" error in Salesforce

In Apex code, Lists can hold duplicate values but, if it contains duplicate sObject IDs and you try to update or delete, you'll get the error : "System.ListException: Duplicate id in list".

We can fix this problem in a simple way:

  1. Create a map of <id,sobject>
  2. Convert the list to Map so that the duplicate IDs are removed.
  3. Update or Delete the values part of the Map.

For example:

// pick up any id from your salesforce org, in this sample it is account id. 
Id aid = '0017F000002WkkdQAC';

List<Account> al = new List<Account>();

for(account a : [select id from account where id ='0017F000002WkkdQAC']){
	Account acc = new Account(id = aid);
	al.add(a);
	al.add(acc);
}
//create a map that will hold the values of the list 
Map<id,account> accmap = new Map<id,account>();

//put all the values from the list to map. 
accmap.putall(al);
if(accmap.size()>0){
	update accmap.values();
}

GDPR Alert

This site uses cookies, including third-party requests, to offer you services in line with your preferences. By closing this banner, scrolling this page or clicking any element, you consent to the use of cookies. If you want to learn more or opt out of all or some cookies, click on Privacy Policy...