The last couple of weeks we have taken a look at both Sets and Lists in Excel, today we will look at Maps the third and final collection. A Map is a collection of key-value pairs, where the key is unique and both the key and value can be of any data type. Typically, the Salesforce Id is used as the key with the record itself as its value. If we were going to create a map of our contacts like our report used to generate our Excel file, column B would be the key and the entire row would be its matching value.
To walk through an example, let’s log into our Development Org and locate Tim Barr’s record. We can easily find Tim’s Contact Id in the Salesforce URL, it will look something like this https://na24.salesforce.com/0031a000003wRFU. Keep in mind that your org may have a different instance as well as a different Contact Id, my particular instance is na24 and for my Tim Barr record the Id is 0031a000003wRFU. Let’s go back into Excel and do an Advanced Search using the Id as the criteria and making sure to check the Match case. The row that the Id is found on is the value associated with the key (Id) in this case.
Now let’s see how this would look in code.
Id myId = Id.valueOf('0031a000003wRFU'); // variable to hold known Salesforce Id
Map<Id,Contact> contactMap = new Map<Id,Contact>([SELECT Id, AccountId, Account.Name, Salutation, FirstName, LastName, Email FROM Contact]); // Map to hold Contact query result
System.debug('My Contact is: ' + contactMap.get(myId)); // Use the known Salesforce Id to get the entire Contact record