Viewing Salesforce Collections in Excel: Lists


Last week we took a look at Sets by using the “Unique records only” filter on a report exported in Excel. This week, we can use the same export to take a look at the Lists collection type, but this time let’s sort the contacts by Last Name.
ContactsExport
A List is similar in nature to a Set, except that the elements are ordered and can contain duplicate items. In the above spreadsheet, if we created a List of Ids for columns A and B and a List of Strings for Columns C and D, all four lists would contain the exact same number of elements and each would be equivalent to the total number of records. Let’s dive back into the code to take a closer look.
1. Log into 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.
The code looks nearly identical to the code we had last week, except this time we are creating List variables and in our database query we asked for the results to be sorted by Last Name, just like in our spreadsheet. Notice that the size of each list is 20, equal to the total number of contacts in our spreadsheet.
ListResults SetsResults
Since a list is an ordered collection of elements, we can retrieve a specific element by its index but keep in mind that the first element is always at index 0. Let’s head back into the code to see more. Replace the code in the execute anonymous window with the following snippet.

Before we look at the debug, let’s see if we can predict the outcome by looking at the first, 10th and last Last Names in our sorted spreadsheet. Unlike the List in Apex, Excels first element is on Row 1 which in our case has the field names, so the 1st contact record is actually found on Row 2, the 10th on Row 11 and the last on Row 21: Bar, Grey and Young. Now let’s see if our debug log matches.

LastNamesResult

Perfect match! For additional fun learning about Salesforce Collections, head on over to WomenCodeHeroes blog, Cooking with Code: Amuse-bouche* of Apex Collections (Lists, Sets, and Maps).

Leave a comment

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