I have a custom object and we have a lot of records of same name under it, how do i make a list with no duplicate values in list
-
You wish to store only those records in the list which have unique name(eliminating all records with same name) right?– AbhijeetCommented Sep 27, 2016 at 6:22
-
@Pankaj Can u please elaborate with some example so that it will easy to understand your query. Lot of records with same name under it means --> Are you referring to a particular Field with column as "Name", also the List u referring is to a List view? Can u confirm?– Robert ThomasCommented Sep 27, 2016 at 6:26
-
@Abhijeet yes -- it's a proper record and that's a list not that list view– Pankaj KumarCommented Sep 27, 2016 at 6:40
3 Answers
Using the following SOQL:
Select Name, count(Id) From Your_Obj__c group by Name Having count(Id) = 1
You can iterate over the list of records(which contains duplicates) and then use a map to store records with key value pair as
(name,record)
Then use the values() method on the map to get records in a list which are all unique.Below is the approach that you can use:
for(Custom_Object__c objCustom:lstDuplicateItems){
mapNameRecords.put(objCustom.name,objcustom);//if duplicate record comes from the list, the previous duplicate record stored in the map will be overridden.
}
List<Custom_Object__c> lstUniqueRecords = mapNameRecords.values();
// lstUniqueRecords now contains unique records
This should work for you :)
If you execute below code in developer console, you can remove duplicare records, assuming you have less than 50000 records. If you have more records then, you need to write a batch class.
List<CustomObject__c> duplicateRecordList = new List<CustomObject__c>();
Set<String> stNames = new Set<String>();
for(CustomObject__c objRecord : [Select Id, Name From CustomObject__c limit 50000])
{
if(stNames.contains(objRecord.Name))
{
duplicateRecordList.add(objRecord);
}
else
{
stNames.add(objRecord.Name);
}
}
delete duplicateRecordList;
Once you remove all duplicates, you can think of setting a Duplicate Management Rule for that Custom Object to avoid duplicates in future.
You can also think of creating a Trigger to avoid duplicate records in future.