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()];
}

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
TechGuy

Tech enthusiastic, life explorer, single, motivator, blogger, writer, software engineer