3

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?

1
  • loop is the only answer I guess. – Ratan Paul May 12 '16 at 16:53
6

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).

3
  • That said, you could effectively accomplish the same thing without a loop using the Map<Id,Object__c> directly from your SOQL, and then just return the name when accessing the Map. Map<Id,Object__c> mapA = new Map<Id,Object__c>([Select Id,Name from Object__c]); String name = mapA.get(Id).Name; – Todd Sprinkel May 12 '16 at 17:24
  • 3
    @ToddSprinkel The problem with that is you have to contend with NullPointerException when the value doesn't exist, while with a Map<Id, String>, you just get null strings instead. – sfdcfox May 12 '16 at 17:34
  • As always, an excellent point @sfdcfox. – Todd Sprinkel May 12 '16 at 17:54
1

You can serialize the map<ID,Sobject> to JSON, apply RegEx substitution/removal to keep only the ID and the Name and then deserialize it from JSON back into a map<ID,String>.

There is a similar idea implemented here:

https://learnsf.wordpress.com/2014/12/29/trick-how-to-obtain-a-map-indexed-by-any-field-not-just-id-faster-and-without-loops/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.