Sub topic 1
Why Apex Has Three Collection Types and How to Choose
Prerequisites
Assume you know basic Apex variables, loops, conditionals, SObjects, and simple SOQL queries.
Why Apex Has Three Collection Types and How to Choose
A collection stores multiple values in one variable. Apex provides three main collection types because programs need different ways to organize data.
| Type | Main property | Typical use |
|---|---|---|
| `List<T>` | Ordered values, including duplicates | Keep records in sequence |
| `Set<T>` | Unique values with no guaranteed order | Remove duplicates or build `IN` filters |
| `Map<K, V>` | Unique keys mapped to values | Find a value quickly by its key |
Choose a List when position or order matters. Choose a Set when each value should appear only once. Choose a Map when you need to look up a value using a key, such as an Account Id.
Lists: Ordered and Indexed
A List<T> stores values in insertion order. T is the type of each element. List indexes start at zero, so the first element is at index 0.
List<String> names = new List<String>{'Ada', 'Grace', 'Ada'};
System.debug(names[0]); // Ada
System.debug(names.size()); // 3Lists allow duplicate values. The list above contains two Ada values. A list can contain primitives, SObjects, or custom Apex objects.
Working with List Methods
Use methods to change and inspect a list:
add(value)appends an element.add(index, value)inserts an element at a position.get(index)reads an element.set(index, value)replaces an element.remove(index)removes and returns an element.contains(value)checks whether a value exists.sort()orders supported values in place.
List<String> names = new List<String>{'Ada', 'Grace'};
names.add('Linus');
names.add(0, 'Alan');
names.set(1, 'Augusta');
System.debug(names.get(1)); // Augusta
names.remove(2);
System.debug(names); // (Alan, Augusta, Linus)An invalid index causes a runtime exception. Check size() before accessing an index when the list might be empty.
Sets: Unique Values
A Set<T> stores each value at most once. Adding an existing value has no effect, and add returns false.
Set<String> tags = new Set<String>{'apex', 'soql'};
Boolean added = tags.add('apex');
System.debug(added); // false
System.debug(tags.size()); // 2Set order is not guaranteed. Use a set for unique Ids, duplicate removal, or a SOQL IN filter. Use a list when you need stable positions or intentional duplicates.
Exercise
Which collection should hold unique Contact Ids before a SOQL IN query?
Show answer
Use a Set<Id>, because it removes duplicates and works as a bind variable.