In Apex, the Set data type is used to represent an unordered collection of unique elements.
Sets do not allow duplicate values, and they provide a way to store and manage a distinct list of items.
The Set data type is often used when you need to ensure that a collection of elements contains no duplicates.
Here's an example of how to declare and use a Set in Apex:
public class SetExample {
public static void main() {
// Declare and initialize a set of integers
Set<Integer> uniqueNumbers = new Set<Integer>{1, 2, 3, 4, 3, 5, 2};
// Add elements to the set
uniqueNumbers.add(6);
uniqueNumbers.add(3); // This won't be added since it's a duplicate
System.debug('Unique Numbers: ' + uniqueNumbers);
// Iterate through the elements in the set
for (Integer num : uniqueNumbers) {
System.debug('Element: ' + num);
}
}
}
We declare a Set named uniqueNumbers that stores integers. We initialize it with a list of integers, including duplicates.
We use the add method to add elements to the set. When we attempt to add a duplicate (e.g., 3), it is not added because sets only allow unique values.
We use System.debug() to print the contents of the uniqueNumbers set. You'll notice that it only contains unique values.
We iterate through the elements in the set using a for-each loop, printing each element. Duplicates are automatically removed in the set.
The Set data type is useful when you need to maintain a collection of distinct elements and ensure that no duplicates exist within that collection.