0

I would like to know if there's a better way to populate a map from a list where conditions apply as to whether the list item is to be added to the map or not.

For eg I have a list of objects related to Accounts, and only where the object meets a condition must it be added to a new map. As there can be multiple objects related to the same Account, only 1 of them will eventually end up in the map.

list<myObject__c> objs = [SELECT Id, Account__c, FieldA__c
                               FROM myObject__c WHERE Account__c IN :accts
                               order by Account__c];

Map<Id, myObject__c> objMap = new Map<Id, myObject__c>();
id actId;
myObject__c internalObj;

for(myObject__c obj : objs){
    if(actId == null) actId = obj.Account__c;
    if(obj.Account__c != actId){
        if(internalobj != null){
            objMap.put(actid, internalobj);
        }
        internalobj = null;
    }
    if(obj.FieldA__c == 'XYZ'){
        internalobj = null;
        break;
    }
    else{
        internalobj = obj;
    }
    actId = obj.Account__c;
}

//Add the last one 
if(internalobj != null){
    objMap.put(actid, internalobj);
}
else{
    objMap.clear();
}

Is there a better way to do this, especially the adding the last item in the list if it applies?

UPDATE: After some rethinking this is much simpler and cleaner and does the trick. The data is shared S2S between 3 orgs (a hub and 2 spokes), but only on conditions being met to ensure it puts the correct information to the correct org.

string spoke = 'OrgA';
Map<Id, myObject__c> objMap = new Map<Id, myObject__c>();
boolean flag = false;
for(myObject__c obj : wobjs){
    flag = false;
    if(objMap.containsKey(obj.Account__c)){
        myObject__c mapobj = objMap.get(obj.Account__c);
        flag = mapobj == null ? true : false;
    }
    if(flag == false){
        if(obj.Origin__c == 'XYZ' || obj.ConfigDetails__c == spoke){
            objMap.put(obj.Account__c, null);
        }
        else{
            objMap.put(obj.Account__c, obj);
        }
    }
}
  • Your example code doesn't make much sense to me. I'm not seeing a reason why you can't just simply do if(obj.FieldA__c == 'XYZ'){objMap.put(obj.Account__c, obj);} and be done with it instead of jumping through all those hoops. Maybe I'm just not getting the gist of what you're trying to do with your current explanation. – Derek F Jul 26 at 0:54
  • It would be better if you can just mention the conditions you need to incorporate inside for loop, on what conditions exactly you need to populate map? – salesforce-sas Jul 26 at 2:29
  • Derek you made me think and I've come up with a better way. It just got a bit complex with the conditions of when to add to the map and when not to and when to overwrite. – Irene Jul 26 at 5:18

Your Answer

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

Browse other questions tagged or ask your own question.