Saturday, 15 July 2023

Duplicate id in list

 

Error 'System.ListException: Duplicate id in list' in Apex :

list can hold duplicate values, but if you try to add duplicate sObject IDs in the list and then update the list you'll get the error. 

Duplicate id in list' in Apex.

List should not hold multiple instances of the same object.

Suppose you are trying to update Account record 

id aid = '0010o000030nWBe';

list <account> al = new list <account>();

for(account a : [select id from account where id ='0010o000030nWBe']){
account acc = new account(id = aid);
    al.add(a);
    al.add(acc);
}
update al;

You will receive error '


To resolve this, we need to create a map and then update

id aid = '0010o000030nWBe';
list <account> al = new list <account>();

for(account a : [select id from account where id ='0010o000030nWBe']){
account acc = new account(id = aid);
    al.add(a);
    al.add(acc);
}
//update al;
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();
}

Duplicate id in list

  Error 'System.ListException: Duplicate id in list' in Apex : list  can hold  duplicate values, but if you try to add duplicate  sO...