Salesforce Collections : Map from SOQL

There must have been times when creating a map from a SOQL is required. I am showing 2 ways of doing the same.

  1. Map from List ( obtained from SOQL)
    Map<Id, CustomObj__c> myMap = new Map<Id, CustomObj__c>();
    for(CustomObj__c objCS : [Select Id Name,Status__c From CustomObj__c ]){
    myMap.put(objCS.Id, objCS);                                                                                                      }
  2. Map directly from SOQL

Map<Id, CustomObj__c> myMap = new Map<String, CustomObj__c>([Select   Id,Name,Status__c From CustomObj__c ]);

However, if you want to put any other field ( other than Id as key, you will have to iterate over the list and put field in the map like approach #1

Map<String, CustomObj__c> myMap = new Map<String, CustomObj__c>();
for(CustomObj__c objCS : [Select Id Name,Status__c From CustomObj__c ]){
myMap.put(objCS.Status__c, objCS);

Permanent link to this article: https://salesforcebuddy.com/2019/01/salesforce-collections-map-from-soql/

Leave a Reply

Your email address will not be published.