Newer Version Available

This content describes an older version of this product. View Latest

Sets

A set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

This table represents a set of strings that uses city names:

'San Francisco' 'New York' 'Paris' 'Tokyo'

Sets can contain collections that can be nested within one another. For example, you can have a set of lists of sets of Integers. A set can contain up to seven levels of nested collections inside it, that is, up to eight levels overall.

To declare a set, use the Set keyword followed by the primitive data type name within <> characters. For example:
1Set<String> myStringSet = new Set<String>();

The following example shows how to create a set with two hardcoded string values.

1// Defines a new set with two elements
2Set<String> set1 = new Set<String>{'New York', 'Paris'};

To access elements in a set, use the system methods provided by Apex. For example:

1// Define a new set
2Set<Integer> mySet = new Set<Integer>();
3// Add two elements to the set
4mySet.add(1);
5mySet.add(3);
6// Assert that the set contains the integer value we added
7System.assert(mySet.contains(1)); 
8// Remove the integer value from the set
9mySet.remove(1);

The following example shows how to create a set from elements of another set.

1// Define a new set that contains the
2// elements of the set created in the previous example
3Set<Integer> mySet2 = new Set<Integer>(mySet);
4// Assert that the set size equals 1
5// Note: The set from the previous example contains only one value
6System.assert(mySet2.size() == 1);

For more information, including a complete list of all supported set system methods, see Set Class.

Note the following limitations on sets:
  • Unlike Java, Apex developers do not need to reference the algorithm that is used to implement a set in their declarations (for example, HashSet or TreeSet). Apex uses a hash structure for all sets.
  • A set is an unordered collection—you can’t access a set element at a specific index. You can only iterate over set elements.
  • The iteration order of set elements is deterministic, so you can rely on the order being the same in each subsequent execution of the same code.