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, 2015 at 17:52

1 Answer 1


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, 2015 at 16:25

You must log in to answer this question.

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