Collections – Apex Programming – Salesforce Certified Platform Developer I Study Guide

4.4 Collections

In Apex, collections are data structures used to store and manage multiple values of the same or different data types. Collections allow you to work with groups of related data in a more organized and efficient way compared to using individual variables. There are three main types of collections in Apex: Lists, Sets, and Maps.

Lists: List elements can be of any data type, including primitive types, collections, and custom data types. They can dynamically resize themselves, meaning you can add or remove elements from a list without specifying its size beforehand. Lists in Apex are typed, which means you specify the type of elements the list will hold. For example, you can have a list of integers, strings, objects, and another. Elements in a list are accessed by their index, starting from 0. For example, the first element in a list is accessed using index 0, the second element using index 1, and so on. Some of the most common methods used while interacting with a list include

•\ add(): Adds an element to the end of the list

•\ get(): Returns the element at the specified index

•\ remove(): Removes the element at the specified index

•\ size(): Returns the number of elements in the list

•\ sort(): Sorts the elements in the list in ascending order

When you add elements to the list using the add() method, the list grows in size. For example, if you add three elements (A, B, and C) to the list, your line now has these elements positioned along it: | A | B | C |

You can remove elements from the list using methods like remove(). If you remove element B, the line looks like this: | A | C |

This Apex code creates a list of strings called names, adds three strings (“Alice,” “Bob,” and “Charlie”) to the list, and then prints the second string (“Bob”) to the system log using System.debug().

List<String> names = new List<String>();

names.add(‘Alice’);

names.add(‘Bob’);

names.add(‘Charlie’);

System.debug(names[1]);

Here’s another example of using a list to store and manipulate names:

List<String> names = new List<String>();

names.add(‘Alice’);

names.add(‘Bob’);

names.add(‘Charlie’);

System.debug(names[1]);

names.remove(0);

for (String name : names) {

System.debug(name);}

Remove the first element (“Alice”) from the list using names.remove(0); then iterate through the modified list (after removing “Alice”), printing each element (“Bob” and “Charlie”) to the system log using a for loop and System.debug(name).

In the third example, we use another method with numbers:

List<Integer> numbers = new List<Integer>();

  • Add elements to the list numbers.add(5); numbers.add(2); numbers.add(8); numbers.add(1);
  • Get the number of elements in the list Integer size = numbers.size(); System.debug(‘Size of the list: ‘ + size);
  • Output: Size of the list: 4
  • Access elements in the list

Integer firstNumber = numbers.get(0); System.debug(‘First number: ‘ + firstNumber); // Output: First number: 5

  • Sort the elements in the list numbers.sort(); System.debug(‘Sorted list: ‘ + numbers);
  • Output: Sorted list: (1, 2, 5, 8)

In this example, we create a list called numbers and add some integer values to it. We then use the size() method to get the number of elements in the list, and the get() method to access the element at index 0 (the first element in the list). Finally, we use the sort() method to sort the elements in ascending order.

Sets: A set is an unordered collection of unique elements. Sets are useful when you want to ensure that there are no duplicate values in your collection. Sets only contain unique elements. If you attempt to add a duplicate element to a Set, the Set will ignore the duplicate value. Unlike Lists, Sets do not have indices. You cannot directly access elements in a Set using an index because Sets are unordered collections. Sets are commonly used when you want to store a collection of unique values, perform set operations, or check for the presence of specific elements in a collection without caring about the order in which they were added. Some commonly used methods to manipulate sets include

•\ add(): Adds an element to the set.

•\ remove(): Removes an element from the set.

•\ contains(): Checks if a specific element is present in the set.

•\ addAll(): Adds all elements from another set to the current set.

•\ retainAll(): Retains only the elements that are present in both sets.

•\ removeAll(): Removes all elements that are present in another set from the current set.

•\ size(): Returns the number of elements in the set.

•\ isEmpty(): Checks if the set is empty.

•\ clear(): Removes all elements from the set.

An example is shown as follows.

Set<Integer> numbers = new Set<Integer>();

numbers.add(5);

numbers.add(10);

numbers.add(5);

System.debug(numbers);

Add two integers, 5 and 10, to the numbers set. Sets do not allow duplicate elements, so the duplicate 5 is ignored. Print the contents of the numbers set, displaying [5, 10] to the system log using System.debug(numbers).

The following is an another example to use a Set to gather all the unique email addresses from a list of contacts:

List<Contact> contacts = [SELECT Email FROM Contact]; Set<String> uniqueEmails = new Set<String>();

for (Contact contact : contacts) { uniqueEmails.add(contact.Email); }

System.debug(‘Unique Email Addresses: ‘ + uniqueEmails);

In this example, the uniqueEmails Set ensures that only distinct email addresses are added, eliminating any duplicates.

We can also use additional methods with names.

Set<String> fruits = new Set<String>();

  • Add elements to the set fruits.add(‘Apple’); fruits.add(‘Banana’); fruits.add(‘Mango’);
  • Get the number of elements in the set Integer size = fruits.size(); System.debug(‘Size of the set: ‘ + size);
  • Output: Size of the set: 3
  • Check if the set is empty

Boolean isEmpty = fruits.isEmpty(); System.debug(‘Is the set empty? ‘ + isEmpty); // Output: Is the set empty? false

  • Check if the set contains a specific element Boolean containsBanana = fruits.contains(‘Banana’); System.debug(‘Does the set contain Banana? ‘ + containsBanana);
  • Output: Does the set contain Banana? true
  • Remove an element from the set

fruits.remove(‘Banana’); System.debug(‘Updated set: ‘ + fruits);

  • Output: Updated set:{Apple, Mango}
  • Clear all elements from the set fruits.clear(); System.debug(‘Cleared set: ‘ + fruits);
  • Output: Cleared set: {}
  • Create another set

Set<String> moreFruits = new Set<String>{‘Orange’, ‘Grapes’};

  • Add all elements from another set fruits.addAll(moreFruits); System.debug(‘Combined set: ‘ + fruits);
  • Output: Combined set: {Orange, Grapes}
  • Iterate over elements in the set

for (String fruit : fruits) {

System.debug(‘Fruit: ‘ + fruit);

}