Preface – This post is part of the Core Apex Tools series.
Lists are the first and most important of the three data types:
List<Contact> peopleToSpam = [SELECT Id, Email FROM Contact];
The reason why Lists are so important is because the output of every SOQL query is a List. The unique aspect of Lists is that they are ordered – had we ordered our SOQL query by Email address, this structure would be preserved in our variable!
Since Lists are ordered, you can get specific elements of your List by the element’s index, or, List position. Indexes start at zero and go all the way up to number of records in your list, minus one! So if you wanted to get specific elements of your List, you could do this using brackets:
Contact firstContact = peopleToSpam; Contact lastContact = peopleToSpam[peopleToSpam.size() - 1];
Notice how we used dot notation to get the size of the List, then subtracted one from this value to get the last element! If our list had 100 elements, we could have gotten the exact same results using peopleToSpam.
You can do some incredible stuff when combining lists and SOQL:
List<String> doNotSpam = new List<String>(); doNotSpam.add('firstname.lastname@example.org');
// Don't want to spam myself! List<Contact> peopleToSpam =[SELECT Email FROM Contact WHERE NOT (Email IN :doNotSpam)];
Take a moment to read over the code and fully understand what it’s doing. I like to pretend I’m a robot when reading code. It really helps to understand how Salesforce interprets your code!
Sets aren’t used as often in Apex – they’re basically lists however they’re unordered and don’t allow any duplicate values. Don’t worry about Sets for now!
Maps are the final type of collection and they’re actually extremely powerful. A map essentially lets you “search” through a list for a particular value! I’ll cover these at a later point – Maps deserve their own post but you won’t need to use them for a while.