Wednesday, 14 March 2018

       System.ListException: Duplicate id in list: 001XXXXXXXXXXXX

Lists can hold duplicate values, but if it contains duplicate sobject IDs and you try to update you'll get the error.

Solution:

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

Sample code :

// 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();
}