Sub topic 2
Working with Set Methods
Assume you know basic Apex syntax, loops, conditionals, SObjects, and simple SOQL queries.
Sets: Unique Values
A Set<T> stores unique values. It does not preserve a useful index order, so use a List<T> when position matters. Adding a duplicate returns false.
Set<String> tags = new Set<String>{'apex', 'soql'};
Boolean addedAgain = tags.add('apex'); // false
Boolean addedNew = tags.add('trigger'); // true
System.debug(tags.size()); // 3
System.debug(tags.contains('soql')); // true
tags.remove('soql');
System.debug(tags.contains('soql')); // falseUseful methods include add, remove, contains, size, isEmpty, and clear. Set methods such as addAll, removeAll, and retainAll work with another set.
Maps: Key-Value Lookup
A Map<K, V> stores one value for each unique key. The key type is K, and the value type is V. Use get for lookup and put to add or replace a value.
Map<String, Integer> scores = new Map<String, Integer>();
scores.put('Ada', 95);
scores.put('Grace', 88);
Integer adaScore = scores.get('Ada'); // 95
scores.put('Ada', 97); // replaces 95
if (scores.containsKey('Linus')) {
System.debug(scores.get('Linus'));
}get returns null when the key is missing. Check with containsKey or test for null before using the result.
Map Methods and Iteration
Common map methods include get, put, remove, containsKey, keySet, values, size, isEmpty, and clear.
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account LIMIT 10]
);
for (Id accountId : accountsById.keySet()) {
Account account = accountsById.get(accountId);
System.debug(account.Name);
}
for (Account account : accountsById.values()) {
System.debug(account.Name);
}A List is usually iterated in order. A Set is iterated value by value, without relying on order.
List<String> names = new List<String>{'Ada', 'Grace'};
for (String name : names) {
System.debug(name);
}
Set<Id> ids = accountsById.keySet();
for (Id accountId : ids) {
System.debug(accountId);
}Collections of SObjects
Collections can store SObjects directly. A map keyed by Id gives fast access to a record, while a set of IDs works well in a SOQL IN condition.
Set<Id> accountIds = accountsById.keySet();
List<Contact> contacts = [
SELECT Id, LastName, AccountId
FROM Contact
WHERE AccountId IN :accountIds
];Exercise
Which collection should you use to collect unique Account IDs before a SOQL IN condition, and which method exposes the IDs from a Map<Id, Account>?
Show answer
Use a Set<Id>. Call keySet() on the map.