RnewPROMO : GET UP TO 20% OFF ON LIVE CLASSES + 2 SELF-PACED COURSES FREE!! - SCHEDULE CALL Rnew

- Salesforce Blogs -

How to List and Set Methods in Salesforce? Learn For A Bright Career



Introduction

Salesforce methods have numerous applications which are used to group data based on different data types. With the increase in remote work, more and more organizations are adopting salesforce to assist the remote sales teams.

9.3 million new jobs and $1.6 trillion new business revenue will be created by the Salesforce economy by 2026.

If you are thinking of making a career in Salesforce, you need to be aware of Apex set and Apex list methods in Salesforce, because the output of the SOQL (Salesforce Object Query Language) query is a list.

Let’s know all whats and whys of Apex List methods and Set methods in salesforce with some examples. 

Let’s First Understand What is Apex and Its Collections?

As we all know, Salesforce is a cloud-based online customer relationship management (CRM) software solution. SalesForce helps marketing, sales, commerce, and service and IT teams to work at a single integrated CRM platform. 

As per Salesforce, Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control statements on SalesForce servers in conjunction with calls to the API. Using syntax that looks like Java and acts like database stored procedures, Apex enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex Code can be initiated by Web service requests and from triggers on objects.  

Apex Collections is a type of variable, it can store numerous records. The different types of Collections are Set, List and Map.

1. Apex Sets

A Set in Salesforce 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.

2. Apex List

An Aapex List is a collection of ordered elements that can be located based on an index. This order follows a definite pattern.

3. Apex Maps

Apex Maps is a collection of key-value pairs with different key maps to a single value. Keys and values can be of primitive types, collections, sObjects, user-defined types, and built-in Apex types.

4. Apex Parameterized Typing

In general, Apex is a statically-typed programming language, which means before a variable can be used, users must specify the data type for a variable.

Moving forward to knowing more about Apex List and Set in Salesforce.

Let’s Dig Deeper Into Apex Set

What Is Apex Set?

  • A Set in Salesforce is an unordered collection of elements that contain any type of data type like primitive types, collections, sObjects, user-defined types, and built-in Apex types.
  • Set methods in Salesforce do not allow duplication. 
  • 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. 

For example:

Setmystrings; SetAcc = new set (); Setcust= new set();

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

What Are Set Methods in Salesforce?

Salesforce Set methods comprise an Apex Set class that is responsible for the gathering of unique elements where duplication of the values of the objects is not allowed. 

The Salesforce Set methods work on a Set — an unordered collection of elements that was initialized using the Set keyword. Set methods are all instance methods, that is, they all operate on a particular instance of a Set.

Set Constructors

Constructors for Set includes:

  • Set()  - It helps in creating a new instance of the Set class. It can hold elements of any data type T.
  • Set(setToCopy) - It helps in creating a new instance of the Set class by copying the elements of the defined Set. T is the data type of the element sets.
  • Set(listToCopy) - It helps in creating a new instance of the Set class by copying the elements in the list. The list can be any data type and the data type of element in the Set is T.

What Are Set Methods in Salesforce and Where Are They Used?

  • add(setElement): It’s used for the addition of an element to the Set if it is not already present.
  • addAll(fromList): It’s used for the addition of all the elements in the specified list to the Set if they are not already present.
  • addAll(fromSet): This is used to add all of the elements in the specified Set to the Set that calls the method if they are not already there.
  • clear(): It is used to remove all of the elements from the Set.
  • clone(): It is used to create a duplicate copy of the Set.
  • contains(setElement): It is helpful in Returning true value if the Set contains the specified element.
  • containsAll(listToCompare): It helps in returning true value if the Set contains all of the elements in the specified list. The list must be of the same type as the Set that calls the method.
  • containsAll(setToCompare): It helps in returning true value if the Set contains all of the elements in the specified Set. The specified Set must be of the same type as the original Set that calls the method.
  • equals(set2): It assists in comparing this Set with the specified Set and returns true if both Sets are equal; otherwise, returns false.
  • hashCode(): It helps in returning the hashcode corresponding to this Set and its contents.
  • isEmpty(): It helps in returning true value if the Set has zero elements.
  • remove(setElement): It helps in removing the specified element from the Set if it is present.
  • removeAll(listOfElementsToRemove): It helps in removing the elements in the specified list from the Set if they are present.
  • removeAll(setOfElementsToRemove): It is helpful in removing the elements in the specified Set from the original Set if they are present.
  • retainAll(listOfElementsToRetain): It is responsible for  Retaining only the elements in this Set that are contained in the specified list.
  • retainAll(setOfElementsToRetain): It helps in retaining only the elements in the original Set that are contained in the specified Set.
  • size(): It helps in returning the number of elements in the Set (its cardinality).
  • toString(): It helps in returning the string representation of the Set.

Let’s have a look at the examples:

Set Methods in Salesforce with Examples

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


set names= new set();
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 will add all values of the set to the other set.


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

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


listmynamelist = new list{'Alaska', 'Arizona ','California','Arkansas' };
set name = new set();
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.


SetmyString = new Set{'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: What Is Process Builder in Salesforce

SetmyString = new Set{'a', 'b'};
SetsString = new Set{'c'};
SetrString = new Set{'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 values that are existing in list or set.


listNames= new list{'Dell','IBM','Apple'};
setOrglist= new set();
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.


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

This method return true if the set has no element
setvalues= new set();
setvalues1= new set{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 setname         {set;get;}
public string selected          {set;get;}
public listacclist     {set;get;}
public listoption {set;get;}

publicpicklistNewExample(){
option= new list();
selectOption op = new selectOption('none','-None-');
option.add(op);
name= new set();
listac=[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();
acclist = [select name,industry,phone,type from account where industry=:selected];
    }
}

Preview

How to Set Methods in Salesforce Apex

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

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()

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

What Are Apex List and Apex List Methods and How Are Those Helpful?

What is an Apex List?

  • A List is an ordered collection of typed primitives, sObjects, user-defined objects, Apex objects, or collections that are distinguished by their indices.
  • A List is an ordered collection, so use the List when you want to identify the List element based on the Index Number. 
  • The List can contain Duplicates and null values.
  • A List should be declared with the “List” keyword. 
  • To define a List, use the List keyword by primitive data, sObject within <> characters. 
  • The index position of the first element in a List always starts with [0], it can grow dynamically at the run. 

List Constructors

The following are constructors for List.

  • List()It helps in creating a new instance of the List class. A List can hold elements of any data type T.
  • List(listToCopy)It helps in creating a new instance of the List class by copying the elements from the specified List. T is the data type of the elements in both lists and can be any data type.
  • List(setToCopy)Creates a new instance of the List class by copying the elements from the specified Set. T is the data type of the elements in the Set and List and can be any data type.

What Is Apex List Methods and Where They Are Used?

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

  • Apex List Methods: add(listElement): It adds an element to the end of the List.
  • Apex List Methods: add(index, listElement): It helps in inserting an element into the List at the specified index position.
  • Apex List Methods: addAll(fromList): It is helpful in the addition of all of the elements in the specified List to the List that calls the method. Both Lists are required to be of the same type.
  • Apex List Methods: addAll(fromSet): It helps in adding all of the elements in the specified set to the List that calls the method. The set and the list need to be of the same type.
  • Apex List Methods: clear(): It is helpful in removing all elements from a List, consequently setting the List's length to zero.
  • Apex List Methods: clone(): It helps in making a duplicate copy of a List.
  • Apex List Methods: contains(listElement): If the List contains the specified element, it returns true.
  • Apex List Methods: deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber): It helps in making a duplicate copy of a List of sObject records, including the sObject records themselves.
  • Apex List Methods: equals(list2): Compares this List with the specified List and returns true if both Lists are equal; otherwise, returns false.
  • Apex List Methods: get(index): It helps in returning the List element stored at the specified index.
  • Apex List Methods: getSObjectType(): It helps in returning the token of the sObject type that composes a List of sObjects.
  • ApexLlist methods: hashCode(): It helps in Returning the hashcode corresponding to theLlist and its contents.
  • Apex List Methods: indexOf(listElement): It helps in returning the index of the first occurrence of the specified element in this List. If this List does not contain the element, it returns -1.
  • Apex List Methods: isEmpty(): It drives true value if the List has zero elements.
  • Apex List Methods: iterator(): It returns an instance of an iterator for this List.
  • Apex List Methods: remove(index): It is responsible for the removal of the List element stored at the specified index, returning the element that was removed.
  • Apex List Methods: set(index, listElement): It sets the specified value for the element at the given index.
  • Apex List Methods: size(): It returns the number of elements in the List.
  • Apex List Methods: sort(): It is responsible for Sorting the items in the List in ascending order.
  • Apex List Methods: toString(): Returns the string representation of the List.

Most of the List methods in Salesforce are similar to set methods in Salesforce and are frequently used by developers to maintain a database app.

Let’s pan over some examples where List methods are used. 

Apex List Methods: add(listElement): It adds an element to the end of the List.

List myList = new List(); 
myList.add(47);
Integer myNumber = myList.get();
system.assertEquals(47, my Number);

Apex List Methods: add(index, listElement): It is responsible for inserting an element into the list at the specified index position.

List myList = new Integer[6]; 
myList.add(0, 47); 
myList.add(1, 52); 
system.assertEquals(52, myList.get(1));

Apex list methods: clone(): It makes a duplicate copy of a list.

The cloned List is similar to the current List.

If this is a List of sObject records, the duplicate List will just be a shallow copy of the List. That is, the sObject records themselves will not be duplicated but the duplicate will have references to each object

For example:

To also copy the sObject records, you must use the deepClone method.

Account a = new Account (Name='Acme', BillingCity='New York');
Account b = new Account(); 
Account[] q1 = new Account[]{a,b};
Account[] q2 = q1.clone(); 
q1[@].BillingCity = 'San Francisco';

System.assertEquals(
'San Francisco',
q1[@]. BillingCity); 
System.assertEquals(
'San Francisco', 
q2[@]. BillingCity);

Apex List Methods: contains(listElement): It returns true if the list has the specified element.
List myStrings = new List{'a', 'b'}; 
Boolean result = myStrings.contains('z'); 
System.assertEquals(false, result);

Apex List Methods: deepClone(preserveId, preserveReadonlyTimestamps, preserveAutonumber)

It makes a duplicate copy of a List of sObject records, including the sObject records themselves

insert q1;
List accts = (SELECT CreatedById, CreatedDate, LastModifiedById,
LastModifiedDate, BillingCity 
FROM Account 
WHERE Name='Acme' OR Name='Salesforce'];

// Clone list while preserving timestamp and user ID fields. 
 Account[] q3 = accts.deepClone(false, true,false);

// Verify timestamp fields are preserved for the first list element. 
System.assertEquals(
accts[0].CreatedById, 
q3[0].CreatedById); 
System.assertEquals(
accts[0].CreatedDate,
q3[0].CreatedDate); 
System.assertEquals(
accts[0].LastModifiedById,
q3[0].LastModifiedById); 
System.assertEquals(
accts[0].LastModifiedDate, 
q3[0]. LastModifiedDate)
;

What Is The Difference Between List and Set in Salesforce?

List and set both are used to group the object. And both are responsible for the extension of the collection interface. The main difference between List and set is:

A List is an ordered collection of elements that are distinguished by their indices. List elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

Whereas, Set is an unordered collection of elements that do not contain any duplicates. Set elements can be of any data type—primitive types, collections, sObjects, user-defined types, and built-in Apex types.

What Is Exactly an Apex Method in Salesforce and How You Can Create one?

An Apex method is defined as the combination of several statements that share some common characteristics and behavior and therefore, they are categorized together so that they can perform a particular operation based on a query.

To use an Apex method you need to call or invoke it. For the creation of the method in the Apex Set class, We can create an Apex Set method by following the syntax given below-

Modifier returnValueType methodName(list of parameters) { // method body; }

A method declaration contains components like a method header and method body that contains the conditions for testing.

The method header specifies the modifiers, return value type, method name, and parameters of the method. Here is a brief description for all.

Modifiers:

The modifier is optional and it tells the compiler how to call the

method. This defines the access type of the method.

Return Type:

A  method may return a value. The  return value type  is  the  data

Type of the value that the method returns. Some methods perform the required

operations without returning a value. In this case, the return value type is void.

Method Name:

This is the actual name of the method. The method name and the parameter List together construct the method signature.

Parameters:

A parameter is similar to a placeholder. When you invoke a method, you pass a value to the parameter. This value is referred to as an actual parameter or argument. The parameter  List refers to the type, number, and order of the parameters of a method. Parameters are optional;  that is, a method may be without any parameters.

Method  Body:

The method body contains a collection of statements that define what the method does.

Pro Tip: You can master all these terms and get prepared for the interviews by reading this blog on Salesforce interview questions and answers.

Can the Apex List Methods and Set Methods Lead to a Bright Career?

So, you made it till now, you covered what is Set and List in salesforce. You must have an idea till now why it is important to learn these methods in Salesforce to secure a salesforce career and excel in the same. 

Did you know the average salary of a Salesforce developer in the US? It is $111,502, know more about the salary of different profiles in Salesforce. And as I have already mentioned, the Salesforce ecosystem is going to add 9.3 million new job opportunities by 2026. You can be one of those 9.3 million deserving candidates by learning all about salesforce. You can check the salesforce career path here and can get started now. 

Many questions from Set and List methods come in Salesforce exams, so, If you need proper guidance and advanced training in your journey of becoming a salesforce professional and want to add value to your resume by getting an industry-recognized certificate, enrol in our salesforce training program now.

Salesforce Tutorial Overview

fbicons FaceBook twitterTwitter google+Google+ lingedinLinkedIn pinterest Pinterest emailEmail

     Logo

    Deepa Jalli

    Deepa, creativity fanatic, who does ample market research to create engaging and insightful content to lead our digital learners towards success in the IT & every other thriving industry.


Comments

  • M

    markyjones

    Great Work, Thanks the above code works for me any issues from here after I can solve

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us

  • Z

    Zane Brown

    Wow! It's working fine. Thank you very much.

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us

  • J

    james

    That was really helpful, I would like to learn more about these methods.

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us

  • J

    Jacky

    Can you tell me more about other collections?

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your query. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us

  • C

    corbin

    I was finding this information for a long time, well described, thanks, team.

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your experience. For further information, you can connect to us at https://www.janbasktraining.com/contact-us

  • C

    Clayton Adams

    I am in the final year of Btech in CS, can I go for a career in Salesforce?

     Reply
    • Deepa User

      JanbaskTraining

      Hey, Thanks for sharing your query. Yes you can go for a Salesforce Career, for more detail, you can connect to us at https://www.janbasktraining.com/contact-us

Trending Courses

AWS Course

AWS

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

Upcoming Class

4 days 09 Dec 2022

DevOps Course

DevOps

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

Upcoming Class

3 days 08 Dec 2022

Data Science Course

Data Science

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

Upcoming Class

4 days 09 Dec 2022

Hadoop Course

Hadoop

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

Upcoming Class

4 days 09 Dec 2022

Salesforce Course

Salesforce

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

Upcoming Class

4 days 09 Dec 2022

QA Course

QA

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

Upcoming Class

4 days 09 Dec 2022

Business Analyst  Course

Business Analyst

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

Upcoming Class

4 days 09 Dec 2022

MS SQL Server Course

MS SQL Server

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

Upcoming Class

4 days 09 Dec 2022

Python Course

Python

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

Upcoming Class

12 days 17 Dec 2022

Artificial Intelligence  Course

Artificial Intelligence

  • Components of AI
  • Categories of Machine Learning
  • Recurrent Neural Networks
  • Recurrent Neural Networks
Artificial Intelligence  Course

Upcoming Class

4 days 09 Dec 2022

Machine Learning Course

Machine Learning

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

Upcoming Class

39 days 13 Jan 2023

Tableau Course

Tableau

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

Upcoming Class

4 days 09 Dec 2022

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews