Did you know that you can directly convert a list of objects into a map in Apex?
Consider the following scenario:
Retrieve all the Opportunities of the given Contacts.
Approach 1:
public static void calc1(List<Contact> conList){
List<Id> conIdList = new List<Id>();
for(Contact con : conList){
conIdList.add(con.id);
}
List<Opportunity> oppList = [SELECT Id, name FROM Opportunity WHERE ContactId IN :conIdList];
}
Approach 2:
public static void calc2(List<Contact> conList){
Map<Id, Contact> IdConMap = new Map<Id, Contact>(conList);
List<Opportunity> oppList = [SELECT Id, name FROM Opportunity WHERE ContactId IN :IdConMap.keySet()];
}