function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Satya Prakash 11Satya Prakash 11 

How to update List containing Duplicate values

Hello All,
Can anyone tell me how to update a list which contains Duplicate values. As we know that list can hold duplicate values but will not update if it contains duplicate values.
I tried to convert the list to Set or Map to hold unique values but the problem is we cannot perform DML operation on Set ot Map.

Any help is highly appreciated!
Best Answer chosen by Satya Prakash 11
Bhanu MaheshBhanu Mahesh
Hi Satya,

Lets suppose your list is of type contact
List<Contact> lstContacts //This list has duplicates
Use Map
Map<Id,Contact> mapContacts = new Map<Id,Contact>();
for(Contact con : lstContacts){
	mapContacts.put(con.Id,con);
}
if(!mapContacts.values().isEmpty()){
	update mapContacts.values();
}

You can use Map instead of list whenever you think there is a possibility of duplicates. and update its values();

Regards,
Bhanu Mahesh

All Answers

BalajiRanganathanBalajiRanganathan
I would suggest to follow the approach

1) Create a new list for dml operation
2) create a set to hold list of id
3) Iterate the duplicate list
4) in the loop check if the set of id has the id. add to new list only if id does not exists


something similar to this.
List<Sobject> newList = new List<SObject>();
Set<Id> idList = new Set<Id>();

for (Sobject obj : oldList) {
  if (idList.add(obj.get('id'))) {
     newList.add(obj);
  }
}

insert newList;

 
CLKCLK
1)Create the map<ID,Object> mapUniqueObjects
2)then dml statement: update mapUniqueObjects.values();
Bhanu MaheshBhanu Mahesh
Hi Satya,

Lets suppose your list is of type contact
List<Contact> lstContacts //This list has duplicates
Use Map
Map<Id,Contact> mapContacts = new Map<Id,Contact>();
for(Contact con : lstContacts){
	mapContacts.put(con.Id,con);
}
if(!mapContacts.values().isEmpty()){
	update mapContacts.values();
}

You can use Map instead of list whenever you think there is a possibility of duplicates. and update its values();

Regards,
Bhanu Mahesh
This was selected as the best answer