[SalesForce] Build a Map from a List

Assuming I have the following objects

Map<id,String> mapA = new Map<id,String>();
List<Object__c> listA =new List<Object__c>([Select id,name from Object__c]);

for(Object__c obj : listA)
mapA.put(obj.id,obj.name);

Instead of creating a map of by looping through the elements of the list, is there a faster more efficient way of achieving this?

I know that I can get some thing like Map<id,Object__c> mapA= new Map<id,Object__c>([Select id from Object__c]);
but I only want to store a name string not the whole Object__c. Is it possible to achieve this or looping through a list is the only option?

Best Answer

Per Map of sObjects, the special auto-mapping constructor only works on entire SObject values.

When working with SOQL queries, maps can be populated from the results returned by the SOQL query. The map key should be declared with an ID or String data type, and the map value should be declared as an sObject data type. (Emphasis mine)

You can't map anything other than the Id field of the SObject for the key, and you can't map anything other than the SObject itself for the value. Any other type of map must use a loop to populate the values. As I've pointed out in other answers, you can also map AggregateResult by using a Map<Id, AggregateResult> map when one of the fields that are grouped is an ID data type and aliased with the value Id (case sensitive).

Related Topic