Usually in trigger, we work on updating related lists we end up querying sObject and looping over it. Or we also make a MAP from that list of records which will create lots of loops and iterations. To avoid this. Salesforce provide us with a simple feature where you can write a SOQL query and return MAP directly.
Here you need a Map<Id, SObject> type return value. To do this, you can use the same as a return type variable for a SOQL query.
Syntax:
Map<Key_Data_Type, List<SObject> m_Map_Variable_Name = new Map<Key_Data_Type, List<SObject>([Select ID, Name From sObject]);
SOQL Query should be part of object instantiation’s constructor. You CANNOT create an instance of an object first and then get query result into MAP. SOQL should be part of constructor only.
Here, Key_Data_Type can be an Id, Integer, String.
sObject can be a standard or a custom sObject.
Example,
Map<Id, Contact> m_Contacts = [Select Id, Name, Email, Phone From Contact Where AccountId IN: l_Account_Ids]
Above query will create a MAP of sObjects with key as ID of that record and value as a record of sObject. You can also create a Nested Query to get related list information.