Data Structures

Apex Sets

Working with Sets

Apex sets use Set<T> for unique elements.

Introduction to Apex Sets

Apex Sets are a collection type in Salesforce that allows you to store unique elements. The elements in a set are unordered and duplicate-free, making sets ideal for situations where you need to ensure that no duplicates exist.

In Apex, a set is defined using the Set syntax, where T represents the data type of the elements you wish to store. Sets are particularly useful for managing collections of primitive data types and sObjects.

Creating and Initializing Sets

Creating a set in Apex is straightforward. You can initialize a set with or without initial values. Below are examples of how to create and initialize a set:

Adding and Removing Elements

You can add or remove elements from a set using the add(), addAll(), remove(), and removeAll() methods. Sets automatically prevent duplicate values from being added.

Checking for Element Membership

You can check whether a set contains a specific element using the contains() method. This can be useful to verify the presence of an element before performing operations on it.

Iterating Over a Set

Since sets are collections, you can iterate over them using a for-each loop. This is useful for processing or displaying the elements within a set.

Use Cases for Apex Sets

Apex Sets are particularly useful in scenarios where you need to:

  • Ensure that a list of records or elements contains no duplicates.
  • Perform efficient membership tests to check the presence of elements.
  • Collect unique values from a query result or list.

Using sets can simplify your logic and improve the efficiency of your Apex code.

Data Structures

Previous
Maps