Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 36 ยท Apex Basics

Collections: Lists, Sets and Maps in Apex

Master Apex collections: ordered Lists, unique Sets and key-value Maps, with the methods, iteration patterns and bulk-friendly idioms every trigger relies on.

Collections hold many values in one variable. In Apex they matter more than in most languages, because Salesforce queries return lists of records and triggers receive lists of records. The three collection types are List (ordered, duplicates allowed), Set (unordered, unique) and Map (key to value). Learn them well: nearly every bulk-safe solution is built from them.

List

A list is an ordered collection with zero-based indexes.

Java
List<String> names = new List<String>();
names.add('Ada');
names.add('Grace');
names.add('Alan');

List<Integer> nums = new List<Integer>{ 5, 3, 9 };   // initial values
String first = names[0];            // array-style access
names.set(1, 'Hopper');
names.remove(2);
names.sort();                       // alphabetical
Integer size = names.size();
Boolean has = names.contains('Ada');
names.addAll(new List<String>{ 'X', 'Y' });
names.clear();
Boolean empty = names.isEmpty();

Index errors throw System.ListException ("List index out of bounds"), so check size() first. Lists can hold any type, including records: List<Account> is the most common collection in Apex.

Set

A set stores each value at most once and has no guaranteed order. Use it for "have I seen this?" checks and to collect unique Ids.

Java
Set<String> cities = new Set<String>{ 'Paris', 'Rome' };
cities.add('Paris');        // ignored: already there
cities.add('Oslo');
cities.contains('Rome');    // true
cities.remove('Rome');
cities.size();              // 2

Sets of Ids are the usual input to a SOQL IN filter: [SELECT Id FROM Contact WHERE AccountId IN :accountIds]. Strings in sets are compared case-sensitively, unlike the == operator.

Map

A map links unique keys to values:

Java
Map<String, Integer> stock = new Map<String, Integer>();
stock.put('apples', 12);
stock.put('pears', 4);
Integer n = stock.get('apples');         // 12; null if the key is missing
Boolean known = stock.containsKey('kiwi');   // false
Set<String> keys = stock.keySet();
List<Integer> values = stock.values();
stock.remove('pears');

Putting an existing key again replaces the value. get on a missing key returns null, not an error, so test with containsKey when null is a valid value.

Apex has a special constructor that turns a list of records into a map keyed by Id, very handy in triggers:

Java
Map<Id, Account> byId = new Map<Id, Account>([SELECT Id, Name FROM Account LIMIT 10]);

Grouping with Map of Lists

The most important collection pattern is "group records by a key". You create a Map<Key, List<Value>>. Check whether the list exists before adding:

Java
Map<Id, List<Contact>> contactsByAccount = new Map<Id, List<Contact>>();
for (Contact c : contacts) {
    if (!contactsByAccount.containsKey(c.AccountId)) {
        contactsByAccount.put(c.AccountId, new List<Contact>());
    }
    contactsByAccount.get(c.AccountId).add(c);
}

After one query for all contacts you can read any account's contacts from the map without another query. This is the heart of bulkification.

Stand-in: group and count in Java

The same pattern in Java uses computeIfAbsent. Here we group orders by customer and count unique customers with a set.

Java Stand-in (Java): group by key with a Map of Lists

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Iterating

Java
for (String name : names) { System.debug(name); }          // for-each
for (Integer i = 0; i < names.size(); i++) { ... }         // classic
for (String key : stock.keySet()) { System.debug(key + '=' + stock.get(key)); }

Do not add to or remove from a list while you are looping over it in a for-each; it throws an exception. Build a second list of items to keep or to remove instead.

Sorting and comparing

List.sort() works on primitives, strings and anything implementing Comparable. You can implement Comparable on your own class to sort records by custom rules:

Java
public class Product implements Comparable {
    public String name;
    public Decimal price;
    public Integer compareTo(Object other) {
        Product p = (Product) other;
        if (price == p.price) return 0;
        return (price > p.price) ? 1 : -1;
    }
}

Choosing the right collection

Need Use
Keep order, allow repeats List
Unique values, fast contains Set
Look up by key Map
Group by key Map<Key, List<Value>>
Collect Ids for a query Set<Id>

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which collection guarantees each element appears at most once?

    A Set ignores attempts to add a duplicate. Lists allow repeats; map keys are unique but map values are not.
  2. 2. What does map.get('missing') return when the key does not exist?

    Missing keys give null, so use containsKey when you need to tell "absent" from "null value".
  3. 3. Which exception occurs when you read names[10] on a list of 3 items?

    Out-of-range access raises System.ListException.
  4. 4. Which type is most useful for a SOQL IN filter on record Ids?

    A Set<Id> (or List<Id>) can be bound with IN :ids, and a set removes duplicates automatically.

Summary

  • List is ordered and allows duplicates; Set is unique and unordered; Map stores key-value pairs.
  • Map get returns null for a missing key; use containsKey to test.
  • new Map<Id, SObject>(listOfRecords) builds an Id-keyed map in one line.
  • Grouping with Map<Key, List<Value>> is the key bulk pattern in Apex.
  • Never modify a list while iterating over it with for-each.

Next: Control Flow and Loops