Understanding deciding, Loops and Collections in Apex

Last updated on Nov 24 2021
Abha Kulkarni

Table of Contents

Understanding deciding, Loops and Collections in Apex

Decision-making structures require that the programmer specify one or more conditions to be evaluated or tested by the program, alongside a press release or statements to be executed if the condition is decided to be true, and optionally, other statements to be executed if the condition is decided to be false.
In this blog, we’ll be studying the essential and advanced structure of decision-making and conditional statements in Apex. Decision-making is important to regulate the flow of execution when certain condition is met or not. Following is that the general sort of a typical decision-making structure found in most of the programming languages

salesforce 72
salesforce

 

Sr.No. Statement & Description
1 if statement

An if statement consists of a Boolean expression followed by one or more statements.

2 if…else statement

An if statement can be followed by an optional else statement, which executes when the Boolean expression is fake.

3 if…elseif…else statement

An if statement can be followed by an optional else if…else statement, which is extremely useful to test various conditions using single if…else if statement.

4 nested if statement

You can use one if alternatively, if statement inside another if alternatively, if statement(s).

 

Apex – Loops

Loops are used when a specific piece of code should be repeated with the specified number of iteration. Apex supports the quality traditional for loop also as other advanced sorts of Loops. during this chapter, we’ll discuss intimately about the Loops in Apex.
A loop statement allows us to execute a press release or group of statements multiple times and following is that the general from of a loop statement in most of the programming languages −

salesforce 73
salesforce

The following tables lists down the various Loops that handle looping requirements in Apex programing language . Click the subsequent links to see their detail.

Sr.No. Loop Type & Description
1 for loop

This loop performs a group of statements for every item during a set of records.

2 SOQL for loop

Execute a sequence of statements directly over the returned set o SOQL query.

3 Java-like for loop

Execute a sequence of statements in traditional Java-like syntax.

4 while loop

Repeats a press release or group of statements while a given condition is true. It tests the condition before executing the loop body.

5 do…while loop

Like a while statement, except that it tests the condition at the top of the loop body.

 

Apex – Collections

Collections may be a sort of variable which will store multiple number of records. for instance , List can store multiple number of Account object’s records. allow us to now have an in depth overview of all collection types.

Lists

List can contain any number of records of primitive, collections, sObjects, user defined and inbuilt Apex type. this is often one among the foremost important sort of collection and also, it’s some system methods which are tailored specifically to use with List. List index always starts with 0. this is often synonymous to the array in Java. an inventory should be declared with the keyword ‘List’.
Example
Below is that the list which contains the List of a primitive data type (string), that’s the list of cities.

List ListOfCities = new List();
System.debug('Value Of ListOfCities'+ListOfCities);
Declaring the initial values of list is optional. However, we'll declare the initial values here. Following is an example which shows an equivalent .
List ListOfStates = new List {'NY', 'LA', 'LV'};
System.debug('Value ListOfStates'+ListOfStates);
List of Accounts (sObject)
List AccountToDelete = new List (); //This are going to be null
System.debug('Value AccountToDelete'+AccountToDelete);
We can declare the nested List also . It can go up to 5 levels. this is often called the Multidimensional list.
This is the list of set of integers.
List myNestedList = new List();
System.debug('value myNestedList'+myNestedList);

List can contain any number of records, but there’s a limitation on heap size to stop the performance issue and monopolizing the resources.
Methods for Lists
There are methods available for Lists which we will be utilized while programming to realize some functionalities like calculating the dimensions of List, adding a component , etc.
Following are some most often used methods −
• size()
• add()
• get()
• clear()
• set()
The following example demonstrates the utilization of of these methods

// Initialize the List
List ListOfStatesMethod = new List();

// This statement would give null as output in Debug logs
System.debug('Value of List'+ ListOfStatesMethod);
// Add element to the list using add method
ListOfStatesMethod.add('New York');
ListOfStatesMethod.add('Ohio');

// This statement would give ny and Ohio as output in Debug logs
System.debug('Value of List with new States'+ ListOfStatesMethod);

// Get the element at the index 0
String StateAtFirstPosition = ListOfStatesMethod.get(0);

// This statement would give ny as output in Debug log
System.debug('Value of List initially Position'+ StateAtFirstPosition);

// set the element at 1 position
ListOfStatesMethod.set(0, 'LA');

// This statement would give output in Debug log
System.debug('Value of List with element set initially Position' + ListOfStatesMethod[0]);

// Remove all the weather in List
ListOfStatesMethod.clear();

// This statement would give output in Debug log
System.debug('Value of List'+ ListOfStatesMethod);
You can use the array notation also to declare the List, as given below, but this is often not general practice in Apex programming −
String [] ListOfStates = new List();

Sets

A Set may be a collection type which contains multiple number of unordered unique records. a group cannot have duplicate records. Like Lists, Sets are often nested.
Example
We will be defining the set of products which company is selling.

Set ProductSet = new Set{'Phenol', 'Benzene', 'H2SO4'};
System.debug('Value of ProductSet'+ProductSet);

Methods for Sets
Set does support methods which we will utilize while programming as shown below (we are extending the above example) −

// Adds a component to the set
// Define set if not defined previously
Set ProductSet = new Set{'Phenol', 'Benzene', 'H2SO4'};
ProductSet.add('HCL');
System.debug('Set with New Value '+ProductSet);

// Removes a component from set
ProductSet.remove('HCL');
System.debug('Set with removed value '+ProductSet);

// Check whether set contains the actual element or not and returns true or false
ProductSet.contains('HCL');
System.debug('Value of Set with all values '+ProductSet);

Maps

It is a key value pair which contains the unique key for every value. Both key and value are often of any data type.
Example
The following example represents the map of the merchandise Name with the merchandise code.

// Initialize the Map
Map ProductCodeToProductName = new Map
{'1000'=>'HCL', '1001'=>'H2SO4'};

// This statement would give as output as key value pair in Debug log
System.debug('value of ProductCodeToProductName'+ProductCodeToProductName);
Methods for Maps
Following are a couple of examples which demonstrate the methods which will be used with Map −
// Define a replacement map
Map ProductCodeToProductName = new Map();

// Insert a replacement key-value pair within the map where '1002' is vital and 'Acetone' is value
ProductCodeToProductName.put('1002', 'Acetone');

// Insert a replacement key-value pair within the map where '1003' is vital and 'Ketone' is value
ProductCodeToProductName.put('1003', 'Ketone');

// Assert that the map contains a specified key and respective value
System.assert(ProductCodeToProductName.containsKey('1002'));
System.debug('If output is true then Map contains the key and output is:'
+ ProductCodeToProductName.containsKey('1002'));

// Retrieves a worth , given a specific key
String value = ProductCodeToProductName.get('1002');
System.debug('Value at the required key using get function: '+value);

// Return a group that contains all of the keys within the map
Set SetOfKeys = ProductCodeToProductName.keySet();
System.debug('Value of Set with Keys '+SetOfKeys);

Map values could also be unordered and hence we should always not believe the order during which the values are stored and check out to access the map always using keys. Map value are often null. Map keys when declared String are case-sensitive; for instance, ABC and abc are going to be considered as different keys and treated as unique.
So, this brings us to the end of blog. This Tecklearn ‘Understanding Decision Making, Loops and Collection in Apex’ blog helps you with commonly asked questions if you are looking out for a job in Salesforce. If you wish to learn Salesforce and build a career in Salesforce domain, then check out our interactive, Salesforce Certification Training: Admin 201 and App Builder, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Salesforce Certification Training: Admin 201 and App Builder

Salesforce Certification Training: Admin 201 and App Builder

About the Course

Salesforce Certification Training course will help you pass the Salesforce Administrator Exam (Admin 201) and the Salesforce App Builder (Dev 401) Exam. Concepts on Force.com Platform, AppExchange, SFDC Security Model, Service Cloud, Sales Cloud, Lightning App Builder, Salesforce Reports & Dashboard can be mastered in this Salesforce Training course. You can also configure the platform, manage users, find better ways to use the platform’s features, build applications with Salesforce Lightning, and more. Further, in this Salesforce certification training course, you will master App builder, Apex, Visualforce, etc.

Why Should you take Salesforce Admin 201 and App Builder Training?

• As per Indeed.com data, 200% global jump in Salesforce jobs since Jan 2016. Salesforce Certified Administrators earn an annual average salary of $87,000 but can go as high as $160,000 depending on their knowledge, skills, and experience.
• More than 200,000 companies worldwide use Salesforce platform. Salesforce leads the CRM market with 19.5 percent of market share – Forbes.
• The global CRM software market will reach US$40.26 billion in 2023, up from US$36.9 billion (2020) – Statista.

What you will Learn in this Course?

Salesforce Fundamentals
• Introduction to CRM concepts and Cloud computing
• Salesforce.com Overview and Fundamentals
• Understanding Salesforce Platform
Understanding Salesforce Platform
• Understanding Salesforce Terminologies and Introducing the force.com platform
• Understanding Salesforce Metadata and API
• Describe the capabilities of the core CRM objects in the Salesforce schema
• Identify common scenarios for extending an org using the AppExchange
• About Salesforce Certification
Introduction to Sales Cloud
• Sales Cloud
• Sales Process
• Sales Productivity Features
• Lead Management
• Lead auto response
• Lead assignment
• Web to lead
• Accounts and Contacts Management
• Opportunities
• Campaign Management
Security Model, User Management and Its Features
• Security Model Mind Map
• System Level or Org Level Security
• User Administration and Troubleshooting
• Permission Sets
• Profile Management
• User Actions
• Assigning Permission
• Session settings
• Activations
• Page layout assignment
• Tab setting
• Field level security
Object, Record and Field Level Features
• Custom Object
• Custom Field
• Data Types
• Relationship among Objects
• Working with App and Tabs
Data Handling and Processing
• Data Import and Export with Salesforce
• Insert, Update and Delete Data with Salesforce
• Export Data with UI
• Export Data using Data Loader Tool
Deployment
• SandBox
• Moving Data from SB to Production – Deployment
• Types of SandBox
• Change Sets
• Types of Change Sets
Application Cycle
• Milestones
• Sandboxes
• Change Sets
• Packages
Reports and Dashboards
Declarative Implementation in Salesforce
Salesforce Development and Apex Programming
• Apex Programming
• Apex Classes
• Apex Settings
• SOQL – Salesforce Object Query Language
• DML Commands
• Apex Class in Detail
• Apex Triggers
• Apex Testing
• Access Specifier in Salesforce
• Testing
Lightning in Salesforce
• Lightning Components
• Lightning Component Capabilities
• Lightning Components vs. Visualforce
Visual Force in Salesforce
• Standard Visualforce controller and controller extensions,
• Visualforce Page
• Understanding the MVC Pattern
• Tools for Visualforce Development
• Visual Force Components
WorkFlows in Salesforce
• Work Flows in Salesforce
• Types of Work Flows
• Work Flows Rules
About Preparation of Salesforce 201 and App Builder Certification exams

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Understanding deciding, Loops and Collections in Apex"

Leave a Message

Your email address will not be published. Required fields are marked *