Header$type=social_icons

What Is a SET In Apex?

A set is an unordered collection of typed primitives, sObjects. For example, the following table is a visual representation of a set of Strings. But Sets do not allow duplicate values to be stored in them.

Clear Method: Removes all the elements from the Set and sets the size of the Set to Zero.

// Clear the elements from Set
Set<Integer> numSet = new Set<Integer>(20,10,30);
numSet.clear(); // Removes all elements from the numSet.
Set<String> nameSet = new Set<String>('Nagarjun','Malli','Hari');
NameSet.clear() //Removes all names from the nameSet.

Clone Method: Creates a new Set and adds all the elements of an existing Set into that new Set.

// Clone the numset to newnumset
Set<Integer> numSet = new Set<Integer>(20,10,30);
Set<Integer> newnumset = numset.clone(); //Creates a duplicate copy all elements from the numSet into newnumset.
// Clone Strings from nameset to newnam
Set<String> nameSet = new Set<String>('Nagarjun','Malli','Hari');
Set<Integer> newnameSet = nameset.clone(); //Creates a duplicate copy all elements from the nameSet into newnameset.
// Clone s-Object
Set<Account> accSet = new Set<Account>(a1,a2,a3);
Set<Account> newaccSet = accSet.clone() //Creates a new Set newaccSet and virtually creates the new elements a1,a2,a3 into it.

IsEmpty Method: Boolean method which returns true if the Set has no elements.

// Empty the Set
Set<String> nameSet = new Set<String>{'Nagarjun','Malli','Hari'};
nameSet.clear(); //all the elements are now removed from the nameSet using the clear method, the nameSet will now be empty and hence isempty method will return true.
system.debug('The name Set is ' + nameSet.isempty());
Result:- 13:32:49:023 USER_DEBUG [3]|DEBUG|The name Set is true

Size Method: Return the number of the elements stored in the Set.

// Find the Set size
Set<String> nameSet = new Set<String>{'Nagarjun','Malli','Hari'};
Integer I = nameSet.size(); // the nameSet size is 3
system.debug('Number of elements in nameSet are' + nameSet.size());
Result:- 13:32:49:023 USER_DEBUG [3]|DEBUG| Number of elements in nameSet are 3