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. For example, the following 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 four levels of nested collections inside it, that is, up to five levels overall.

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

The following are ways to declare and populate a set:

1Set<String> s1 = new Set<String>{'a', 'b + c'}; // Defines a new set with two elements
2Set<String> s2 = new Set<String>(s1); // Defines a new set that contains the 
3                                     // elements of the set created in the previous step

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

1Set<Integer> s = new Set<Integer>(); // Define a new set
2s.add(1);                            // Add an element to the set
3System.assert(s.contains(1));        // Assert that the set contains an element
4s.remove(1);                         // Remove the element from the set

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. Do not rely on the order in which set results are returned. The order of objects returned by sets may change without warning.

    When you activate the critical update called “Predictable Iteration Order for Apex Unordered Collections” in Spring ’15, the order of returned results is no longer arbitrary. The order of elements is deterministic—the order is the same every time you run the same code again.

    Note