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:
- Create a map of <id,sobject>
- Convert the list to Map so that the duplicate IDs are removed.
- 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();
}