[SalesForce] Retrieving results from a map

I'm trying to work with and understand maps.
I have the following map and I don't know how to retrieve one of the results from it, can some one explain what I'm doing wrong?

Map<String, RecordType >RecTypeList = new map<String, RecordType>([select Name, id from RecordType
                         where sObjecttype = 'Service_call_Task__c' 
                         AND  DeveloperName IN ('Service','Alarm')]) ;
system.debug(RecTypeList);
system.debug(RecTypeList.get('Alarm'));

The first debug line returns the id of the recordtype and then the results of the SOQL Query

{0124E00000010OaQAI=RecordType:{Name=Service, Id=0124E00000010OaQAI}, 0124E00000010P9QAI=RecordType:{Name=Alarm, Id=0124E00000010P9QAI}}

I was expecting something like Alarm = 0124E00000010P9QAI

The second debug line returns a null result.

I've tried to change the map from

<String, RecordType> to <String, Id >

but i get an error:

Invalid initializer type List found for Map: expected a Map with the same key and value types, or a valid SObject List

Best Answer

Here is the approach:

Map<Id, RecordType> RecTypeMap = new map<Id, RecordType>([SELECT id, Name  from RecordType
                                                     where sObjecttype = 'Service_call_Task__c' 
                                                     AND  DeveloperName IN ('Service','Alarm')]) ;
for(Id recId:RecTypeMap.keySet())
{
    RecordType rdObject = RecTypeMap.get(recId);
    String recName = rdObject.Name;
}

Ideally, to retrieve the RecordType information you do not need to perform separate SOQL query. You can do that by using Schema class.

Schema.DescribeSObjectResult R = Service_call_Task__c.SObjectType.getDescribe();
List<Schema.RecordTypeInfo> lstRT = R.getRecordTypeInfos();
for(Schema.RecordTypeInfo rt:lstRT)
{
    System.debug('RecordTypeName=' + rt.getName());
    if(rt.getName().contains('Service') || rt.getName().contains('Alarm'))
    {
         System.debug('RecordTypeId=' + rt.getRecordTypeId());
    }
}
Related Topic