Loops in Salesforce Apex

Loops in Salesforce Apex

On January 17, 2024, Posted by , In Salesforce Apex Tutorial, With Comments Off on Loops in Salesforce Apex

Table of Contents:

What is a Loop?

A loop is a block of code that is repeated until a specified condition is met. Salesforce apex supports both traditional and advanced loop types. Using a loop statement, we can execute a statement or group of statements multiple times.

Below is the flow diagram of a loop followed by most programming languages.

CRS Info Solutions offers a comprehensive and dynamic Salesforce online course career building program for beginners, covering admin, developer, and LWC concepts. This course features immersive real-time projects, interactive hands-on learning, detailed daily notes, essential interview questions, thorough certification preparation, and strategic job prep guidance. Join their inspiring free demo to embark on an exciting Salesforce journey with expert mentorship and unlock your full potential in the Salesforce ecosystem. Enroll for a free demo today!

do {statement} while (Boolean_condition)

The do-while loop is a control flow statement in programming that executes a block of code at least once and then repeatedly as long as a specified condition is true. It differs from a traditional while loop in that it guarantees at least one execution of the code block, regardless of the condition, because the condition is evaluated after the code block has executed. This makes it particularly useful in scenarios where the code needs to run at least once before checking a condition, such as processing user input or iterating over a collection with an unknown number of elements.

The loop consists of the do keyword followed by the code block, and then the while keyword with the condition in parentheses. If the condition is true after the first execution, the loop continues; otherwise, it exits, and the program continues with the next statement after the loop.

Syntax:

do {
   code_block
}
 while (condition);

Counting Down: This loop starts with a count value of 5 and decrements it in each iteration. The loop continues as long as count is greater than 0. It’s useful for counting down from a specific number.

Integer count = 5;

do {
    System.debug('Count: ' + count);
    count--;
} while (count > 0);

Summing Numbers:

This loop calculates the sum of the first five positive integers. It starts with number set to 1 and adds it to sum in each iteration, incrementing number by 1 each time. The loop runs until number is greater than 5.

Integer sum = 0;
Integer number = 1;

do {
    sum += number;
    number++;
} while (number <= 5);

System.debug('Sum: ' + sum);

Using a Boolean Condition:

This loop uses a Boolean variable continueLoop to control its execution. It starts with count set to 1 and increments it in each iteration. When count reaches 3, it sets continueLoop to false, causing the loop to exit. This pattern is useful when the loop’s continuation depends on a condition that might change within the loop’s body.

Boolean continueLoop = true;
Integer count = 1;

do {
    System.debug('Count: ' + count);
    if (count == 3) {
        continueLoop = false;
    }
    count++;
} 
while (continueLoop);

Processing a List:

This loop iterates through a list of strings (fruits) and prints each element. It uses an index variable to track the current position in the list and increments it in each iteration. The loop continues as long as index is less than the size of the list, ensuring that each element is processed.

List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};
Integer index = 0;

do {
    System.debug('Fruit: ' + fruits[index]);
    index++;
} 
while (index < fruits.size());

while (Boolean_condition) statement;

A while loop in Apex executes a block of code repeatedly until a particular Boolean condition is satisfied. A while loop is used to repeatedly execute a block of code as long as a specified condition evaluates to true . Here’s an improved and more detailed version of the code block, along with an explanation:

Syntax:

// Initialize a counter variable
int counter = 0;

// Use a while loop to execute the code block as long as the counter is less than 5
while (counter < 5) {
    // Inside the loop, print the value of the counter
    System.out.println("Counter: " + counter);

    // Increment the counter to avoid an infinite loop
    counter++;
}

In this example:

  • The condition counter < 5 is checked before each iteration of the loop. As long as this condition is true , the loop continues to execute.
  • The code block inside the loop prints the current value of counter and then increments it by 1 using counter++ .
  • The loop will execute a total of 5 times, printing the values of the counter from 0 to 4. Once counter reaches 5, the condition counter < 5 evaluates to false , and the loop terminates.

for (initialization; Boolean_exit_condition; increment) statement;

Apex provides three variants of for loop:

The Standard for loop:

In Salesforce Apex, a for loop is a control flow statement that allows you to execute a block of code repeatedly, with a specified number of iterations or until a certain condition is met. There are two main types of for loops in Apex: the traditional for loop and the for-each loop.

Here’s a sample code snippet of a traditional for loop in Apex:

Syntax:

// Define a list of integers
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};

// Use a traditional for loop to iterate over the list and double each number
for (Integer i = 0; i < numbers.size(); i++) {
    // Access and modify each element in the list
    numbers[i] = numbers[i] * 2;
    System.debug('Doubled Number: ' + numbers[i]);
}

In this example:

  • The loop starts with an initialization expression ( Integer i = 0 ), which sets the starting index for iteration.
  • The condition ( i < numbers.size() ) is checked before each iteration. The loop continues as long as this condition evaluates to true .
  • After each iteration, the increment expression ( i++ ) is executed to update the loop counter.
  • Inside the loop, the code accesses each element of the numbers list using the loop counter i and doubles its value. The updated value is then printed to the debug log.

The list or set iteration for loop:

Syntax:

// Define a list of strings representing fruit names
List<String> fruits = new List<String>{'Apple', 'Banana', 'Cherry'};

// Use a for-each loop to iterate over the list of fruits
for (String fruit : fruits) {
    // Inside the loop, you can access and perform operations on each fruit
    System.debug('Fruit: ' + fruit);
    // Additional code to perform operations on each fruit
}

In this example:

  • String is the data type of the elements in the list. You can replace this with any other data type or sObject type as needed.
  • fruit is the loop variable that represents each individual element in the list.
  • fruits is the list being iterated over. You can also use a set instead of a list.
  • Inside the loop, you can access the current element using the loop variable ( fruit ) and perform any necessary operations.

The for-each loop is a convenient and readable way to iterate over collections in Apex. It abstracts away the need for using indices to access elements, making the code cleaner and less error-prone, especially when working with complex data structures.

The SOQL for loop:

Syntax:

// Define a SOQL query to retrieve a list of Account records
String soqlQuery = 'SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000';

// Use a SOQL for loop to iterate over the query results
for (Account acc : Database.query(soqlQuery)) {
    // Inside the loop, you can access and manipulate each Account record
    System.debug('Account Name: ' + acc.Name);
    // Additional code to perform operations on each record
}

In this example:

  • Account is the sObject type we’re querying. You can replace this with any other sObject type as needed.
  • acc is the loop variable that represents each individual record returned by the SOQL query.
  • Database.query(soqlQuery) is used to execute the SOQL query string dynamically. You can also use a static query directly in the loop, like for (Account acc : [SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000]) .
  • Inside the loop, you can access the fields of each Account record using dot notation (e.g., acc.Name ) and perform any necessary operations.

Using a SOQL for loop is efficient because it processes the records in batches, reducing the number of queries and the amount of heap space used, which is particularly important in Apex due to governor limits.

for (variable : array_or_set) statement;

In a list or set loop, the elements in a list or set are iterated over. The for (variable : array_or_set) statement in Apex, also known as the for-each loop, is a powerful and concise way to iterate over elements in a collection, such as an array, list, or set. This looping construct simplifies the process of accessing and manipulating each element in the collection, making the code more readable and easier to maintain. By eliminating the need for explicit indexing, the for-each loop reduces the chances of errors and enhances code clarity, making it a preferred choice for developers when working with collections in Salesforce’s Apex programming language.

Syntax:

// Define a list of integers
List<Integer> numbers = new List<Integer>{1, 2, 3, 4, 5};

// Use a for-each loop to iterate over the list
for (Integer num : numbers) {
    // Inside the loop, you can access and manipulate each element
    System.debug('Number: ' + num);
    // Additional code to perform operations on each element
}

In this example:

  • Integer is the data type of the elements in the list. You can replace this with any other data type or sObject type as needed.
  • num is the loop variable that represents each individual element in the list.
  • numbers is the list being iterated over. You can also use a set instead of a list.
  • Inside the loop, you can access the current element using the loop variable (e.g., num ) and perform any necessary operations.

for (variable : [inline_soql_query]) statement;

The SOQL for loop iterates over all the sObject records that the SOQL query returns. The Salesforce Object Query Language (SOQL) for loop is a powerful feature in Apex, Salesforce’s proprietary programming language, that allows developers to iterate over a set of records retrieved by a SOQL query. This construct is particularly useful for efficiently processing large volumes of data while adhering to Salesforce’s governor limits. By leveraging SOQL for loops, developers can easily access, manipulate, and perform operations on each record in the result set, making it an essential tool in the development of custom Salesforce applications and functionalities.

Syntax:

// Define a SOQL query to retrieve a list of Account records
String soqlQuery = 'SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000';

// Use a SOQL for loop to iterate over the query results
for (Account acc : Database.query(soqlQuery)) {
    // Inside the loop, you can access and manipulate each Account record
    System.debug('Account Name: ' + acc.Name);
    // Additional code to perform operations on each record
}

In this example:

  • Account is the sObject type we’re querying. You can replace this with any other sObject type as needed.
  • acc is the loop variable that represents each individual record returned by the SOQL query.
  • Database.query(soqlQuery) is used to execute the SOQL query string dynamically. You can also use a static query directly in the loop, like for (Account acc : [SELECT Id, Name FROM Account WHERE AnnualRevenue > 1000000]) .
  • Inside the loop, you can access the fields of each Account record using dot notation (e.g., acc.Name ) and perform any necessary operations.

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training institute Pune to gain practical, hands-on experience. Our training covers all essential aspects of Salesforce, ensuring comprehensive learning. Enroll for free demo today!

Comments are closed.