BLACK FRIDAY OFFER: Flat 50% Off with Free Self Learning Course | Use Coupon BLACKFRIDAY50

- Salesforce Blogs -

How to Set and List Methods in Salesforce Apex?

Introduction

Salesforce methods are used to group data based on different data types. Some of the important examples get set methods in salesforce and list methods in Salesforce. The reason why list methods in apex are so important because the output of the SOQL query is a List. Lists are basically ordered collection of data and frequently used within databases. The objective of this blog is to make you familiar with list methods in Salesforce and get set methods in Salesforce.

What is set?

A set is an unordered collection of elements that contain any type of data types like primitive types, collections, sObjects, user-defined types, and built-in Apex types. Set methods in Salesforce do not allow duplicate. The insertion order is not preserved in the set. It also grows dynamically in run time like a list. You cannot perform DML with Set. To declare a set, use the Set keyword followed by the primitive data type name within <> characters. Moving ahead, get set methods in Salesforce are generally used together as needed.

For example:


Set<string>mystrings;
Set<account>Acc = new set<account> ();
Set<CustomObject__c>cust= new set<CustomObject __c>();

Set is a collection type which contains multiple numbers of unordered unique records. A Set cannot have duplicate records Like Lists.

Learn Salesforce in the Easiest Way

  • Learn from the videos
  • Learn anytime anywhere
  • Pocket-friendly mode of learning
  • Complimentary eBook available

Read: What Is Interesting About Salesforce Internships?

Set Methods in Salesforce

  • add(setElement)
  • addAll(fromList)
  • addAll(fromSet)
  • clear()
  • clone()
  • contains(setElement)
  • containsAll(listToCompare)
  • containsAll(setToCompare)
  • retainAll(listOfElementsToRetain)

Ø removeAll(setOfElementsToRemove)

  • isempty():

add(setElement): Adds an element to the set if it is not already present.


set<string> names= new set<string>();
names.add('Jack');
names.add('Steve');
names.add('jorge');
names.add('Jack');
system.debug(names);
system.debug(names.size());//3

Here we have added ‘jack’ two times but set will not allow duplicate value, so debug output is Jack, Steve, and Jorge.

addAll(fromset) This method willaddallall value of the set to the other set.


Set<String> state = new Set<String>{'Alaska', 'Arizona ','California','Arkansas' };
set<String> s2 = new set<String>(state);
system.debug(s2);

addAll(fromlist): Adds all of the elements in the specified list to the set if they are not already present.


list<String>mynamelist = new list<String>{'Alaska', 'Arizona ','California','Arkansas' };
set<String> name = new set<String>();
name.add('Virginia');
name.addAll(mynamelist);
system.debug(name);// {Alaska, Arizona , Arkansas, California, Virginia}

Contains (Element); Returns true if the set contains the specified element.


Set<String>myString = new Set<String>{'ABC', 'XYZ'};
Boolean result =myString.contains('ABC');
Boolean result1 = myString.contains('AXZ');
System.debug(result);//True
System.debug(result1)//False

containsAll(setToCompare): Returns true if the set contains all of the elements in the specified set.

Read: Confused About How to Learn Salesforce Development? Here is the way!

Set<String>myString = new Set<String>{'a', 'b'};
Set<String>sString = new Set<String>{'c'};
Set<String>rString = new Set<String>{'a', 'b', 'c'};

Boolean result1, result2;
result1 = myString.addAll(sString);
System.debug(result1);//True
result2 = myString.containsAll(rString);
System.debug(result2);// True

retainAll(listOfElementsToRetain): This will keep only the value that areexisting in list or set.


list<string>Names= new list<string>{'Dell','IBM','Apple'};
set<string>Orglist= new set<string>();
Orglist.add('Dell');
Orglist.add('Sony');
Orglist.add('Acer');
Orglist.add('HP');
boolean result;
result=Orglist.retainall(names);
system.debug(result);//True

removeAll(setOfElementsToRemove)

This method will remove the elements in the specified list from the set if they are present.


set<integer>values= new set<integer>{10,20,30,40};
set<integer>ages= new set<integer>{10,20,30};
values.removeAll(ages);
system.debug(values);
isempty():

This method return true if the set has no element
set<integer>values= new set<integer>();
set<integer>values1= new set<integer>{10,20};
boolean flag=values.isempty();
boolean flag1=values1.isempty();
system.debug(flag);//True
system.debug(flag1);//false
How to use set in example

Apex class
public class picklistNewExample {
public set<string>name         {set;get;}
public string selected          {set;get;}
public list<account>acclist     {set;get;}
public list<selectOption>option {set;get;}

publicpicklistNewExample(){
option= new list<selectoption>();
selectOption op = new selectOption('none','-None-');
option.add(op);
name= new set<string>();
list<account>ac=[select industry,name,type,phone from account where industry != null];
for(account a:ac){
name.add(a.industry);  

     }
for(string b:name){
SelectOption op1 = new selectOption(b,b);
option.add(op1);
     }

    }
public void DisplayRecord(){
acclist = new list<account>();
acclist = [select name,industry,phone,type from account where industry=:selected];
    }
}

<apex:page controller="picklistNewExample" id="page" >
<apex:sectionHeader title="Account Record" description="PickList" help="help" />
<apex:form id="fm">
<apex:pageblock title="Choose PickList" tabStyle="Lead" id="pb" >
<apex:pageblocksection title="Select One" id="pbs">
<apex:selectList size="1" value="{!selected}">
<apex:selectOptions value="{!option}"/>
<apex:actionSupport event="onchange" action="{!displayRecord}"/>
</apex:selectList>
</apex:pageblocksection>
<apex:pageBlockSection title="Selected Records" rendered="{! !IsNull(acclist)}">
<apex:pageBlockTable value="{!acclist}" var="a"  >
<apex:column value="{!a.name}" />
<apex:column value="{!a.industry}" />
<apex:column value="{!a.type}" />
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageblock>
</apex:form>
</apex:page>

Preview

How to Set Methods in Salesforce Apex

Till the time, we have discussed set methods in Salesforce with examples. Moving ahead, let us see list methods in Apex Salesforce.

Salesforce Training For Administrators & Developers

Read: An Introduction to Apex Class in Salesforce for Beginners
  • No cost for a Demo Class
  • Industry Expert as your Trainer
  • Available as per your schedule
  • Customer Support Available

List Methods in Salesforce:

Here are quick details of list methods in Salesforce and all of them are instance methods.

  • add(listElement)
  • add(index, listElement)
  • addAll(fromList)
  • addAll(fromSet)
  • clear()
  • clone()
  • contains(listElement)
  • deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber)
  • equals(list2)
  • get(index)
  • getSObjectType()
  • hashCode()
  • indexOf(listElement)
  • isEmpty()
  • iterator()
  • remove(index)
  • set(index, listElement)
  • size()
  • sort()
  • toString()

Most of the list methods in Salesforce are similar to set methods in Salesforce and frequently used to developer to maintain a database app.

Salesforce Training For Administrators & Developers

  • Personalized Free Consultation
  • Access to Our Learning Management System
  • Access to Our Course Curriculum
  • Be a Part of Our Free Demo Class

Final Words:

With this blog for methods in Salesforce, you have a sound idea of getting set methods in Salesforce and list methods in Salesforce. Similarly, there are more methods and Salesforce objects that can be utilized for different purposes. To know more about Salesforce methods or Salesforce objects, or Salesforce Apex classes, salesforce batch classes, join online classes at JanBask training right away!

Read: Salesforce Admin Interview Questions and Answers


Salesforce Tutorial Overview


    Janbask Training

    A dynamic, highly professional, and a global online training course provider committed to propelling the next generation of technology learners with a whole new way of training experience.


Comments

Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

4 days 04 Dec 2020

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

14 days 14 Dec 2020

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

9 days 09 Dec 2020

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

11 days 11 Dec 2020

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

4 days 04 Dec 2020

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

5 days 05 Dec 2020

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

4 days 04 Dec 2020

MS SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

4 days 04 Dec 2020

Python

  • Features of Python
  • Python Editors and IDEs
  • Data types and Variables
  • Python File Operation

Upcoming Class

0 day 30 Nov 2020

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks

Upcoming Class

5 days 05 Dec 2020

Machine Learning

  • Introduction to Machine Learning & Python
  • Machine Learning: Supervised Learning
  • Machine Learning: Unsupervised Learning

Upcoming Class

-1 day 29 Nov 2020

Tableau

  • Introduction to Tableau Desktop
  • Data Transformation Methods
  • Configuring tableau server
  • Integration with R & Hadoop

Upcoming Class

19 days 19 Dec 2020

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews