I am trying to remove duplicates from a List of Custom Objects.

This is what I am doing:

Set<CustomObject> mySet = new Set<CustomObject>();
mySet.addAll(originalList); //OriginalList contains duplicate Custom Objects.
System.debug(mySet.size()); //This always prints the same size of the original list

I don't know what is wrong happening here, When I see the list of items using debug there are clearly two Objects with same details.

Anything am I missing??

  • 1
    This may help you understand what's going on.
    – BarCotter
    Mar 12 '15 at 15:36
  • 2
    @BarCotter , Thanks for the link. I ended up adding the implementation for equals and hashCode method and now it is working fine.
    – javanoob
    Mar 12 '15 at 16:46

The Ids of records of that CustomObject are different. So the values in the set are different(each record is unique) and that's why they are not de-duplicated. If you want to use the Set based approach, clone each record and add it to the Set.

Set mySet = new Set();

for(CustomObject co : originalList) { mySet.add(co.clone()); }

//Check the size

  • Just tried it and I am still seeing the same size.. Do you think I should provide implementation for equals and hashCode method for my Custom Object??
    – javanoob
    Mar 12 '15 at 16:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.