I am wondering if it's possible to create something similar to this:

Map<sObject.field, sObject> mapOfsObject = new Map<sObject.field, sObject> ([
  SELECT field
  FROM sObject

I know this is possible with the Id of the sObject. But I cannot make it work for a different field. Is it even possible?

1 Answer 1


You can't automatically assign an SObject map by any value other than Id. For any other field, you have to use a standard loop:

for(SObject record: [...]) {
    mapOfSObject.put(record.Field__c, record);
  • I usually do that for loop but was hoping that there could be a way to avoid using it. Thank you.
    – Arthlete
    Commented Mar 23, 2016 at 22:30
  • It would be nice if this were possible without the for loop to manually build the map...but I'd pray for the soul of the poor sap who got stuck with trying to implement that feature.
    – Derek F
    Commented Mar 24, 2016 at 1:04
  • 1
    @DerekF I think it'd be simple, actually... just provide an extra map parameter: new Map<String, SObject>(Account.Name, [select ...]). In fact, all they'd have to do is generalize the code that's already there.
    – sfdcfox
    Commented Mar 24, 2016 at 1:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .