Viewing Salesforce Collections in Excel: Sets

When writing your first trigger in Apex one of the most stressed best practices is to bulkify your code. One key to bulkification is the use of Salesforce Collections. Salesforce has three different classes used for collections: Sets, Lists and Maps. Today we will take a closer look at Sets using the results of a Contacts Report in Excel.
The spreadsheet below contains 9 columns with 21 rows of data. The first row is the header column which is the label for each field extracted. The data is a simple report ran in a Developer Org that includes the Account ID, Contact ID, Account Name, Salutation, First Name, Last Name, Title, Mailing Street and Email. A Set is an unordered collection of unique values that can contain any data type but for this exercise we will stick with primitive data types like IDs and Strings.
All Contacts

If we went through and added each AccountID in column A to a set there would only be a total of 12 elements, this is because a Set contains unique elements with no duplicate values. Since the report is on Contacts and an Account can have one or more Contacts we would expect that the Set would only keep one unique AccountID. We can view the 12 records in Excel by highlighting column A and going to the Advanced Filters and checking the Unique Records only.


Unique Filter and Resulting AcctIds
If we went ahead and added all of the ContactIDs in column B to a Set then we would expect to see all 20 IDs in the Set, this is because each Contact has its own unique Salesforce ID. We should expect Column C to give us the same results we saw with column A because in this scenario all of our Accounts have unique names, however that is not always the case because an Org could easily have multiple Accounts with the same Name in a different city or state. Can you figure out how many elements would be added to a Set for column D? You guessed it, only 2!
Now let’s take a look at how we would actually add these elements to a Set and verify our results from above.
1. Open your Developer Org
2. Launch the Developer Console
3. Select Open Execute Anonymous Window from the Debug Menu
4. Enter the following code snippet:

5. Press the Execute button (Verify the Open Log option is checked)
Note: You may need to set your user to be monitored in the Debug Logs for the Logs to appear. Results may vary depending on the records in your Developer Org.
Want to learn more about Sets and/or Collections, one of my all time favorite resources is a blog by Jeff Douglas called “Fun with Salesforce Collections“.

Leave a comment

Your email address will not be published. Required fields are marked *