0

I am trying to remove duplicate and creating a set and list with non duplicate values related to field ord__c . Trying to minimize the code as far as possible. Let me know if I can handle the same using the below piece of code I am using :

 Set < Id > OrId = new Set < Id > ();
 Integer j = 0;
        while (j < ListR.size())
        {
          OrId.add(ListR.get(j).Ord__c);
          if(OrId.contains(ListR.get(j).Ord__c))
          {
            ListR.remove(j);
          }
          else
          {
            j++;
          }
        }
1
  • It is very difficult to eliminate duplicate value in your case, In case if list[0] has Name="order1" and ord__c="id1" and list[1] has Name="order2" and ord__c="id1", Both has "ord__c" id is same and different names , Its very difficult blindly delete on of the record without any further verification.
    – NITHESH K
    Commented Nov 24, 2017 at 5:12

2 Answers 2

3

Not sure if I understand what you are doing, but there are a couple things you might change here:

  • you should never modify the list, your are iterating over.
  • this line is useless: if(OrId.contains(ListR.get(j).Ord__c)) it's always true.

What kind of reduces your code to something like this:

Set<Id> OrId = new Set<Id>();
while (0 < ListR.size()) {
    OrId.add(ListR.get(0).Ord__c);
    ListR.remove(0);
}

How about using a simple for loop?

Set<Id> idSet= new Set<Id>();
for(CustomObject__c record : ListR) {
    idSet.add(record.Ord__c);
}

Set values are already unique, so there are no duplicates.

0

It is very difficult to eliminate duplicate value in your case, In case if list[0] has Name="order1" and ord__c="id1" and list[1] has Name="order2" and ord__c="id1", Both has "ord__c" id is same and different names , Its very difficult blindly delete on of the record without any further verification.

In case still you wanted say like including ord__c field, other fields also same, Then you can eliminate using map function by setting Ord__c as key to map by irritating over the list. As a result map does not hold duplicate key.

Map<string, customObjectName > NoDuplicateMap= new map<string, customObjectName >();
for(customObjectName obj : ListR)
     NoDuplicateMap.put(obj.Ord__c, obj);

You must log in to answer this question.

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