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);
}
}
}
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.