APEX COLLECTION: Set

SALESFORCE APEX COLLECTION: Set

SALESFORCE APEX COLLECTION: Set

In this episode, we are gonna discuss the second apex collection i.e. Set.
Let's get started.
SET :- 

It is an unordered collection of elements where elements can be of any data type (primitive type, collections, sObjects, user-defined types, and built-in Apex types).
1. Set don't allow the duplicate values.
2. Insertion order is not preserved in the set.
3. It grows dynamically at run time.

Set can be defined just like List.
For Example:
=============================================
set<string> names = new set<string>();
set<Account> acc = new set<Account>();
set<Customer__c> mycustomers = new set<Customer__c>();

public void add(Object) //This method will add elements to the set.
  set<string> names = new set<string>();
  names.add('one');
  names.add('two');
  names.add('one');
=============================================

NOTE: Set will not allow duplicates, but if we insert it will not raise any error it will not takes value.

Hence the major difference between list and set is it is unordered collection and It will not accept duplicate records.

Now let's understand by one hands-on example to demonstrate set.
Example Controller Class :
=============================================
public class SetExample
{
  public set<string> names {get;set;}
  public setExample()
  {
    names = new set<string>();
    names.add('one');
    names.add('two');
    names.add('Ajinkya');
    names.add('one');
    names.add('one');
   }
}
=============================================

Example Visulaforce Page :
=============================================
<apex:page controller="setExample">
   <apex:pageBlock>
    <apex:pageBlockTable value="{!names}" var="a">
     <apex:column value="{!a}"/>
    </apex:pageBlockTable>
   </apex:pageBlock>
  </apex:page>
=============================================
Now hit !! on preview button for the output result.
Output :
=============================================
SALESFORCE APEX COLLECTION: Set
=============================================

As you can see in the output there are no duplicates.

Hence In this way, you can have all your records without duplicates very smartly.

WOHOOO !! YOU HAVE JUST COMPLETED APEX COLLECTION: SET EPISODE 

If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you 
Happy learning ☁️⚡️ (Learn. Help. Share.)

<< PREVIOUS                                                      NEXT >>

APEX COLLECTION: Set APEX COLLECTION: Set Reviewed by on Rating: 5

No comments:

HELP !! SHARE !! SUGGEST !!

Powered by Blogger.