This method of delayed initialization can be useful for us in scenarios where the value of the variable is computed or fetched from a database query when it’s required in the code.
Variables in Collections
When working with collections, we often declare variables to hold our lists, sets, maps and then populate them when it’s needed.
List<Integer> scores = new List<Integer>{85, 90, 95};
System.debug('Initial Scores: ' + scores);
This inline initialization of a list using curly braces is a shortcut that will be particularly useful for us when the values are known at the time of declaration.
Practical Examples and Real-World Scenario
All these concepts together with the help of a real example will help to understand it quickly. Let’s go through a small example that will represent a common scenario in a Salesforce org: Managing a list of student scores and checking if they passed based on a threshold.
public class StudentScores {
public static void checkPassingScores() {
// Declare and initialize a list of student scores
List<Integer> scores = new List<Integer>{72, 85, 67, 90, 55};
// Initialize a set to store passing scores (no duplicates)
Set<Integer> passingScores = new Set<Integer>();
Integer passingThreshold = 70;
// Loop through the scores list
for (Integer score : scores) {
if (score >= passingThreshold) {
passingScores.add(score);
}
}
System.debug('Passing Scores: ' + passingScores);
}
}
Below Screenshot Shows Actual Output for above code in debug log:
- We start by creating a list of scores values.
- We define a passing threshold and then use a loop to iterate through the scores.
- If a score meets or exceeds the threshold, it will be added to a set, making sure that duplicate scores will not be recorded.
- Finally, the result is logged using System.debug as an output shown in above snapshot.
This example demonstrates variable declaration, initialization and control structures in Apex and also shows the practical usage of collections to solve daily problems that we might face in activities.