Set in apex salesforce

Collection Set is similar to List but with few differences. It is important to understand these difference as otherwise it can cause failure in the logic that you have written which may not be easily visible during unit testing.

Set unlike List is a collection of elements which are unordered that means you can’t access a set element at a specific index. You can only iterate over set elements.

Second important point related to set is that it does not store duplicate elements. List on the other hand can store duplicate elements.

Set can store below types in it-
Primitive types like integer,string etc or Collections or SObject or user defined types like wrapper class or even built in apex types.

Example- Set<Integer> intSet = New Set<integer>()
Set<Id> idSet = New Set<Id>()

New elements can be added to the set by using add() method or you can add elements directly at the time of declaration as below,
Set<integer> mySet = new Set<integer>{4, 6, 9};

Sets can be nested, that is you can have set of set and this can go up to total five levels. 
Eg Set<Set<Id>> nestedSet
Simialr to List salesforce provides various system methods to manipulate data in set. Below are some of the commonly used methods for set data manipulation.

    Adds a new element to the set.
    Adds all of the elements in the provided list to the set.
    Adds all of the elements in the specified set to the set.
    deletes all of the elements from the set.
    Makes a duplicate copy of the set.

No comments:

Post a comment