Find your content:

Search form

You are here

Avoiding Duplicates in Loop (inside other loops)

 
Share

I have a complicated trigger (a labor of love for over 2 years now). I've recently discovered one of the problems in it. It ends up with duplicate entries in "updateList" to apply to SF (recently bulkified it with help from StackExchange, thank you very much).

if(updateList.get((Account)accObj) == null )
{ // Avoid DUPES...
    updateList.add((Account)accObj);
}

The first line is not right. The .add line is FINE. How do I reference the accObj in the IF (or another way of doing this please??). I thought this would be simple. Silly me.

Thanks all.


Attribution to: AMM

Possible Suggestion/Solution #1

In this case how to avoid duplicate:

Map> mapSectionAgreement = new Map>();

        // Listing Agreement Section Names in to Map
        for(OISP_Agreement__c argmnts:lstAgreement){

            //List<OISP_Agreement__c> sectionNamesList = mapSectionAgreement.get(argmnts.OISP_Agreement_Section__r.name);

            if(mapSectionAgreement.containskey(argmnts.OISP_Agreement_Section__r.name)){
                List<OISP_Agreement__c> sectionNamesList = mapSectionAgreement.get(argmnts.OISP_Agreement_Section__r.name);
                sectionNamesList.add(argmnts);
                mapSectionAgreement.put(argmnts.OISP_Agreement_Section__r.name,sectionNamesList);
            } 
            else{
                List<OISP_Agreement__c> sectionNamesList = new List<OISP_Agreement__c>();
                sectionNamesList.add(argmnts);
                mapSectionAgreement.put(argmnts.OISP_Agreement_Section__r.name,sectionNamesList);
            }
        }

Attribution to: Eswar

Possible Suggestion/Solution #2

You're best using a Map to avoid dupes, as you can easily check if the AccountId already exists as a key value in the Map.

Map<String, Account> updateMap = new Map<String, Account>{};

if(!updateMap.containsKey((String)accObj.get('Id')) //check that Acc Id not already added
{ // Avoid DUPES...
    updateMap.put((String)accObj.get('Id'), (Account)accObj);
}

Then when you want to update Accounts, use

Database.update(updateMap.values());

Attribution to: techtrekker
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/3639

My Block Status

My Block Content