09
JunGrab Deal : upto 20% off on live classes - SCHEDULE CALL
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. (Resource: Salesforce)
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 in Salesforce. Here, going through a professional Salesforce Training Certification.
Let’s know all whats and whys of Apex List methods and Set methods in Salesforce with some examples.
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.
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.
An Aapex List is a collection of ordered elements that can be located based on an index. This order follows a definite pattern.
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.
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. Meanwhile, you can go through different Salesforce cloud courses to get expertise in Salesforce.
What Is Apex Set?
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.
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.
Constructors for Set includes:
Let’s have a look at the 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
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
Till this time, we have discussed set methods in Salesforce with examples. Moving ahead, let us see the list of methods in Apex Salesforce.
Here are quick details of list methods in Salesforce and all of them are instance methods.
Till this time, we have discussed Set methods in Salesforce with examples. Moving ahead, let us see Apex list methods in Salesforce.
The following are constructors for List.
Here are quick details of Apex List methods in Salesforce and all of them are instance methods.
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)
In Salesforce, a set is a sorted collection of several element types that include various data types. These data types could be collections, user-defined data types, built-in apex data types, or primitive data types.
Like a list in Salesforce, set items change and expand in a dynamic manner while being used. If you want to make the implication of a set, try using the set keyword first. Then, use the special characters > to enter the name of the primitive's data type.
The set methods in Salesforce are available whenever you need them.
The set methods in Salesforce are available whenever you need them. In general, a set is an ordered mixture of various data kinds that includes the various counts or numbers of the records or datasets in a specific sequence.
When there is no authorization for the values of the objects to be duplicated, set methods in a set class are in charge of collecting unique elements. The primary use of set methods in Salesforce is based on the fact that they initialize a set, which is an ordered collection of elements, using the Set keyboard.
As is common knowledge, the set elements may be in possession of either a built-in or a defined data type that is random or specific. After instance methods, set methods are well-known by another moniker that directs us toward using a specific method. To implement sets of various data types, we also require a set function Object() { [native code] } and set method.
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 sent and List in Salesforce is:
A List in Salesforce 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.
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 in Salesforce 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 in Salesforce 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.
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.
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.
Q1. What does a list in Salesforce mean?
Ans:- An ordered group of elements that can be identified by their indices is referred to as a list. Any data type, including primitive types, collections, sObjects, user-defined types, and built-in Apex types, can be used for list elements. This table shows a list of Strings in visual form: Index 0 and Index What are the methods of list in Salesforce?
Following are the methods to do Salesforce lists :
Q2. What to export list in Salesforce?
Ans:- To explore in front of the list in Salesforce, select the checkbox. Press Export. Choose Next. The File and Delivery dialogue box must be finished.
Q3. What is the best way to make a list in Salesforce?
Ans:- In Salesforce lists Classic, create a custom list view.
Q4. What is a set Salesforce?
Ans:- A set Salesforce is a non-duplicate collection of elements that is unordered. Any data type, including primitive types, collections, sObjects, user-defined types, and built-in Apex types, may be used for set elements.
Q5. What is the purpose of using set Salesforce?
Ans:- A set is a non-duplicate collection of primitives or sObjects that are not ordered. Therefore, if you want to guarantee that your collection won't contain duplicates, use set.
Q6. How to create list class Salesforce?
Ans:- You can easily create a new instance of the List class Salesforce just by copying the elements from the specified set.
Q7. What distinguishes arraies from lists in Salesforce?
Ans:- In Apex, lists and arrays are essentially equivalent. The basic data structures and functions of Arrays and Lists are identical, therefore there is no logical difference between them, however the array syntax is more conventional than Java.
Q8. What are the two types of lists in Salesforce?
Ans:- Two different sorts of lists in Salesforce are frequently used in good technical documentation:
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.
AWS
DevOps
Data Science
Hadoop
Salesforce
QA
Business Analyst
MS SQL Server
Python
Artificial Intelligence
Machine Learning
Tableau
Search Posts
Related Posts
A Guide on How to Get & Reset Security Token in Salesforce Lightning
131.2k
16 Amazing Salesforce Features that you Shouldn't Ignore
8.5k
Salesforce Platform Developer 1 Exam Details You should Know!
326.1k
How Long Does It Take To Learn Salesforce? Get a Real Estimate
22.6k
Learn in 2020 how to Create Different Format Reports in Salesforce.
839.6k
Receive Latest Materials and Offers on Salesforce Course
Interviews
markyjones
Great Work, Thanks the above code works for me any issues from here after I can solve
JanbaskTraining
Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us
Zane Brown
Wow! It's working fine. Thank you very much.
JanbaskTraining
Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us
james
That was really helpful, I would like to learn more about these methods.
JanbaskTraining
Hey, Thanks for sharing your understanding. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us
Jacky
Can you tell me more about other collections?
JanbaskTraining
Hey, Thanks for sharing your query. For further insight, you can connect to us at https://www.janbasktraining.com/contact-us
corbin
I was finding this information for a long time, well described, thanks, team.
JanbaskTraining
Hey, Thanks for sharing your experience. For further information, you can connect to us at https://www.janbasktraining.com/contact-us
Clayton Adams
I am in the final year of Btech in CS, can I go for a career in Salesforce?
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