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
Vinnie BVinnie B 

Easy way to take an List with duplicates to one without?

I seem to run into this situation a lot and have been using a brute force way around it.  For example, I query a bunch of contacts for their accounts and put the results into a list.  But this list has duplicate accounts.  I want the list de-duped.  I've tried using the GROUP BY clause of the query but the query results are then aggregate result objects that I have to convert into the object in question.

I've settled on this code which is pretty concise but is a shotgun approach.  I'm thinking there has to be an easier way (using Maps?).  Any comments?

Thanks!!

for (Opportunity anOpp1 : FullListOfOpps) {
        FOUND = false;  // boolean
        for (Opportunity anOpp2 : ListOfOppsWithoutDuplicates) {
           if (anOpp2.Id == anOpp1.Id) {
             FOUND = true;
           }
        }
        if (!FOUND) {
           Opportunity newOpp = new Opportunity();      
           newOpp.id = anOpp1.id;
           ListOfOppsWithoutDuplicates.add(newOpp);
        }
      }
Hermes YanHermes Yan
Map would work. Using the accountId as the key to your map. The order you iterate through your contacts will determine the last contact in the map as each dupe would replace the previous.
kibitzer2kibitzer2
Assuming all opportunities in FullListOfOpps were created with the same set of fields queried, the following, believe it or not, should work:

Set<Opportunity> deDupedOpportunities = new Set<Opportunity>(FullListOfOps);
ListOfOppsWithoutDuplicates = new List<Opportunity>(deDupedOpportunities); // If you want the results in a list.

If there is the possibility that different fields were queried or the opportunity may have different field values in the array,  then you will indeed have to use a map like this:

Map<ID,Opportunity> deDupedMap = new Map<ID, Opportunity>();
for(Opportunity op: FullListOfOpps) deDupedMap.put( op.id, op);
ListOfOppsWithoutDuplicates = deDupedMap.values();

I know you mention accounts in your description, but the code you have doesn't reference them at all - so I'm assuming FullListOfOpps is a list of opportunities and that the source of the list containing duplicate opportunities is not really relavent to the question.