0

I have a query which returns duplicate records. I need to remove all duplicates from it and store all unique records in a list. I'm trying to assign non duplicate records including id to tempList. Please suggest a method to achieve this. Thanks.

    Map<String,temp_object__c> tempMap = new Map<String,temp_object__c>([select id,name,string,string1,string2 from temp_object__c]);
         List<temp_object__c> tempList = new List<temp_object__c>();
         for(String key: tempMap.keyset()){
         //here i need to assign to tempList
}
2
  • what is the criteria to check a record is duplicate Commented May 16, 2018 at 4:23
  • field string1 shouldn't be duplicated
    – Daniel
    Commented May 16, 2018 at 4:25

1 Answer 1

0

Create a Set<String> as set contains only unique values and add the field string1 into unique set and check in the loop if the value doesn't exists in the set then only add the value in the tempList

Set<String> uniqueSet = new Set<String>();
Map<String,temp_object__c> tempMap = new Map<String,temp_object__c>([select id,name,string,string1,string2 from temp_object__c]);
List<temp_object__c> tempList = new List<temp_object__c>();
for(String key: tempMap.keyset()){
   //here i need to assign to tempList
   if(!uniqueSet.contains(tempMap.get(key).string1)){
      //FIRST ADD THE STRING TO SET AND ADD IN THE LIST
      uniqueSet.add(tempMap.get(key).string1);
      tempList.add(tempMap.get(key));
   }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .