I have a custom object that has an ExternalId as one of the fields. Will Apex allow me to build a map with the external id as the key?

I tried the following code

Map<String,Asset_Plans__c> mapAssetSpecs = new Map<String, Asset_Plans__c>([Select AssetNumber__c, Id, Name FROM Asset_Plans__c WHERE AssetNumber IN ('123','245')]);

However this code doesn't change what is being stored in the key! I am still getting Id in the key.

The reason for this is I want to perform a lookup based on the AssetNumber__c column and get the Id of the record.

  • What is the reason for the negative feedback? – abhi Nov 18 '15 at 17:52

If you instantiate a Map and pass it a select statement the key will always be the id of the objects.

To get what you want you need to first query into a List, then iterate the list adding the values keyed by your externalId value.

    List assetPlans = [Your SOQL];
    Map<String, Asset_Plans__c> aMap = new Map<String, Asset_Plans__c>();

    for (AssetPlans__c assetPlan : assetPlans) {
        aMap.put('YOUR_EXT_ID', assetPlan);
  • Thank You! There is a small change you need to make to the code you've posted. You need to correct the syntax for the map you've declared. Map aMap should be Map<string, string> aMap – abhi Nov 18 '15 at 16:25

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.