[SalesForce] Returning a Custom Map from a Query

Is it possible to return a custom map from a SOQL query?

I know we can do this:

Map<Id, Contact> contacts = new Map<Id, Contact>([SELECT Id ... FROM Contact]);

bus is it also possible to have something like this:

Map<String, Decimal> myMap = new Map<String, Decimal>(SELECT name, Amount__c FROM Cust_Obj);

I want the above map to be populated like this, without iterating through a list:

for(Cust_Obj CO : Cust_Obj_List) {
    myMap.put(CO.name, CO.Amount__c);
}

Best Answer

No. You need to loop through for any mapping strategy besides by Id. The for loop is required to map by Name.

There are only three defined constructors on the Map Class:

Map<T1,T2>()

Creates a new instance of the Map class. T1 is the data type of the keys and T2 is the data type of the values.

Signature
public Map<T1,T2>()

Map<T1,T2>(mapToCopy)

Creates a new instance of the Map class and initializes it by copying the entries from the specified map. T1 is the data type of the keys and T2 is the data type of the values.

Signature
public Map<T1,T2>(Map<T1,T2> mapToCopy)

Parameters
mapToCopy
Type: Map<T1, T2>
The map to initialize this map with. T1 is the data type of the keys and T2 is the data type of the values. All map keys and values are copied to this map.

Map<ID,sObject>(recordList)

Creates a new instance of the Map class and populates it with the passed-in list of sObject records. The keys are populated with the sObject IDs and the values are the sObjects.

Signature
public Map<ID,sObject>(List<sObject> recordList)

Parameters
recordList
Type: List<sObject>
The list of sObjects to populate the map with.

There's also the putAll method but it gives you the same result:

putAll(sobjectArray)

Adds the list of sObject records to a map declared as Map or Map.

Signature
public Void putAll(sObject[] sobjectArray)

Parameters
sobjectArray
Type: sObject[]

Return Value
Type: Void

Usage
This method is similar to calling the Map constructor with the same input.

Related Topic