There must have been times when creating a map from a SOQL is required. I am showing 2 ways of doing the same.
- 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); } - 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);