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.
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 aMap<Id, AggregateResult>
map when one of the fields that are grouped is anID
data type and aliased with the valueId
(case sensitive).