How do I use a set in Salesforce?
What is a Set in Salesforce?
Ans - a. Set classes are used to store the elements inside the collection in Sorting Order.
b. Set Collection Doesn't allow duplicate elements inside it.
Syntax of Set Class -
Set<Datatype> objectName = new Set<Datatype>();
e.g. -
Set<String> countryName = new Set<String>();
Methods in Set Class -
1. Add(element_name) - used to add a new element inside the collection.
2. AddAll(collection_name) - used to add a collection of elements to the set collection at a time.
3. size() - it returns the size of the collection.
4. isEmpty - used to check collection is empty or not.
5. clear() - used to remove all elements from the Set.
6. Contains(element_name) - used to Find the element in Collection.
7. remove(element_name) - used to remove a specified element from the collection.
8. equals(collection_name) - used to compare two collections.
e.g. -
Set<Integer> studentAges = new Set<Integer>();
studentAges.add(26);
studentAges.add(29);
studentAges.add(24);
studentAges.add(27);
studentAges.add(25);
System.debug(' Student Ages are : ' +studentAges);
studentAges.remove(24);
System.debug('After Removing Age 24 : '+studentAges);
System.debug('Total Number of Student Age in Collection is:' +studentAges.size());