3

I have two functions that convert a list of SObjects to a map. They do the same thing except that the SObject is different.

How can i combine them to one generic function?

private Map<String, License_Item__c> LicenseItemListToMap(List<License_Item__c> licenseItems) {
    Map<String, License_Item__c> returnMap = new Map<String, License_Item__c>();
    for(License_Item__c item : licenseItems) {
        returnMap.put(item.Name,item);
    }
    return returnMap;
}

private Map<String, License_Item_Limit__c> LicenseItemLimitListToMap(List<License_Item_Limit__c> licenseItemLimits) {
    Map<String, License_Item_Limit__c> returnMap = new Map<String, License_Item_Limit__c>();
    for(License_Item_Limit__c item : licenseItemLimits) {
        returnMap.put(item.Name,item);
    }
    return returnMap;
}
7

You can use the generic sObject:

void recordsByFieldToMap(Map<String, sObject> target, SObjectField field, sObject[] source) {
  for(sObject record: source) {
    target.put((String)record.get(field), record);
  }
}

It would be used like this:

Map<String, License_Item__c> items = new Map<String, License_Item__c>();
recordsByFieldToMap(items, License_Item__c.Name, records);

We take advantage of the fact that we can pass objects by reference (items) to cause changes, and the dynamic sObject.get method lets us extract the field values without fuss. There are other ways to do this as well, but this is the approach I would take.

  • What if i don't want to pass objects by reference, and i want to return a map? – Dana Griff Jan 6 '20 at 9:46

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.