Sub topic 3
Using Collections with SOQL
Assume you know Apex variables, loops, conditionals, SObjects, and basic SOQL. This chapter focuses on using collections together safely.
SOQL results and nested collections
A SOQL query can initialize a List<SObject>. Passing that list to a Map constructor creates a map keyed by record Id. The map’s keySet() returns a Set<Id>, which works well in an IN bind variable.
List<Account> accounts = [
SELECT Id, Name
FROM Account
LIMIT 100
];
Map<Id, Account> accountsById = new Map<Id, Account>(accounts);
Set<Id> accountIds = accountsById.keySet();
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
];
Map<Id, List<Contact>> contactsByAccount =
new Map<Id, List<Contact>>();
for (Contact contactRecord : contacts) {
if (!contactsByAccount.containsKey(contactRecord.AccountId)) {
contactsByAccount.put(
contactRecord.AccountId,
new List<Contact>()
);
}
contactsByAccount.get(contactRecord.AccountId).add(contactRecord);
}A nested collection contains another collection, such as Map<Id, List<Contact>>. This pattern groups each Contact under its Account Id.
Bulk-safe code
Bulk-safe code handles many records in one transaction. Query once outside loops, collect Ids in a Set, and use Maps for lookups. Never run SOQL or DML inside a loop when one operation can handle the whole collection.
Sorting and copying
List.sort() sorts primitives such as Strings and Integers. A custom class must implement Comparable and return a negative, zero, or positive value from compareTo.
public class Employee implements Comparable {
public String name;
public Decimal salary;
public Employee(String name, Decimal salary) {
this.name = name;
this.salary = salary;
}
public Integer compareTo(Object value) {
Employee other = (Employee)value;
if (salary == other.salary) return 0;
return salary < other.salary ? -1 : 1;
}
}Assignment copies a collection reference, so both variables can change the same collection. clone() makes a shallow copy: the collection is new, but contained SObjects are shared. deepClone() also copies the contained SObjects.
Heap size and collection limits
Collections consume heap memory. Query only needed fields and rows, avoid unnecessary nested data, and process large data sets in batches. Exact heap and collection limits depend on the Apex execution context.
Exercise
Which structure groups Contacts by Account Id, and why is the query outside the loop?
Show answer
Use Map<Id, List<Contact>>. The query is outside the loop to avoid repeated SOQL and to support bulk processing.