List isEmpty Apex

Content Index

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.

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.

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

List isEmpty 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.

List isEmpty Apex
FaceBook
List isEmpty Apex
Twitter
List isEmpty Apex
Google+
List isEmpty Apex
LinkedIn
List isEmpty Apex
Pinterest
List isEmpty Apex
Email

    List isEmpty Apex

List isEmpty Apex

List isEmpty Apex

Upcoming Class

3 days 18 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

4 days 19 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

3 days 18 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

3 days 18 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

18 days 02 Apr 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

3 days 18 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

3 days 18 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

10 days 25 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

4 days 19 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

18 days 02 Apr 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

10 days 25 Mar 2022

List isEmpty Apex

List isEmpty Apex

Upcoming Class

10 days 25 Mar 2022