Mastering Apex Logic: A Step-by-Step Guide
Building robust and efficient Apex logic is a cornerstone of Salesforce development. It’s where the rubber meets the road, transforming business requirements into tangible code. To help you sharpen your logical thinking and problem-solving skills, we’ve curated a series of practical scenarios. This is part one in the Logical Scenarios in APEX series. These challenges in the series are designed to simulate real-world situations, allowing you to apply your Apex knowledge in a hands-on manner. Whether you’re a budding developer or a seasoned pro looking to enhance your toolkit, these exercises will push your abilities and expand your understanding of Apex capabilities. Let’s dive in!
#1 ~ Write an Apex method that takes a list of integers and returns a list of those integers squared.
In many Salesforce development scenarios, there are times when you need to perform operations on collections of data, such as lists of numbers. One common requirement is to manipulate each element in a list based on a specific logic or formula. In this post, we will explore how to create an Apex method that processes a list of integers and returns a new list containing the squares of the original integers. This kind of functionality is useful in various applications, from mathematical calculations to data transformations within Salesforce.
public class LogicalApexClass {
/* 1st Approach === Using Math.pow method */
//Creating a method which accepts a list of integers as parameter
public static List<Integer> integerSquaredMethod(List<Integer> intList){
//Creating an instance of a list which will hold the Squared values of integers
List<Integer> squaredIntList = New List<Integer>();
//making sure the list of integers received from the method parameter is not empty
if(!intList.isEmpty()){
//iterating over the list of integers received from the method parameter
for(Integer num : intList){
/* pow(doubleValue, exponent) === method of the Math class
* Returns the value of the first Double raised to the power of exponent.*/
Double squaredNum = Math.pow(num, 2);//Math.pow returns value in Double data type
Integer squaredInt = squaredNum.intValue();//Converting Double to integer
squaredIntList.add(squaredInt);//adding squared numbers to the list we instantiated
}
}
system.debug('this is square==='+squaredIntList);
return squaredIntList;
}
/*=================================== OR ==========================================*/
/* 2nd Approach === Using Simple multiplication */
//Creating a method which accepts a list of integers as parameter
public static List<Integer> integerSquaredMethod(List<Integer> intList){
//Creating an instance of a list which will hold the Squared values of integers
List<Integer> squaredIntList = New List<Integer>();
//making sure the list of integers received from the method parameter is not empty
if(!intList.isEmpty()){
//iterating over the list of integers received from the method parameter
for(Integer num : intList){
//Multiplying the number with itself to get the square value
Integer squaredInt = num * num;
squaredIntList.add(squaredInt);//adding squared numbers to the list we instantiated
}
}
system.debug('this is square==='+squaredIntList);
return squaredIntList;
}
}
Apex#2 ~ Write an Apex method that takes a map of Account IDs to Account Names and returns a list of Account Names that are duplicates.
In Salesforce, dealing with duplicate data can be a common challenge, especially when managing records such as Accounts. Identifying and handling duplicates is crucial for maintaining data integrity and accuracy. In this post, we will demonstrate how to write an Apex method that takes a map of Account IDs to Account Names and returns a list of Account Names that are duplicates. This method can be particularly useful for data cleansing and deduplication processes within your Salesforce environment.
public class LogicalApexClass {
//Creating a method which accepts a Map (key as Id and value as String) as parameter
public static List<String> dublicateAccountNameMethod(Map<Id, String> accMap){
//Creating an instance of a list which will hold duplicate Account Names
List<String> duplicateAccName = New List<String>();
//Creating an instance of a Map which will hold Account Name as key and its count as value
Map<String, Integer> accNameToCountMap = New Map<String, Integer>();
//making sure the Map we received from the method parameter is not empty
if(!accMap.isEmpty()){
//iterating over the Map values of the Map received from the method parameter
for(String accName : accMap.values()){
//As the loop runs we are checking if "accNameToCountMap" has Account Name we are getting from the accMap.values()
//When a new Account Name comes for the first time in "accName" variable it will go into the "else" condition where we will initialize the count as 1
//Then after that with each subsequent occurrence of the same Account Name it will come into "if" condition where we will further increment the count
if(accNameToCountMap.containsKey(accName)){
//Map.get() method takes the key to get the Value stored against the key
Integer count = accNameToCountMap.get(accName);
count = count + 1;//Increment the count with each further occurrence of the same Account Name
accNameToCountMap.put(accName, count);//Adding the Account Name as key and final count of the number of times the Name occurred to the "accNameToCountMap" Map
} else{
//Adding the Account Name as key and value as 1 to the "accNameToCountMap" Map
accNameToCountMap.put(accName, 1);
}
}
}
//Now we have a Map of Account Names to the count of how many times the Name occurred
//Making sure "accNameToCountMap" Map is not empty
if(!accNameToCountMap.isEmpty()){
//Iterating over the keys of "accNameToCountMap" Map
for(String accountName : accNameToCountMap.keySet()){
//Checking if the Account name occurred more than once
if(accNameToCountMap.get(accountName)>1){
//Adding the Account Names which occurred more than once to "duplicateAccName" list
duplicateAccName.add(accountName);
}
}
}
system.debug('this is duplicateAccName==='+duplicateAccName);
return duplicateAccName;
}
}
Apex#3 ~ Create an Apex method that merges two sets of strings and returns the result.
In Salesforce development, working with collections of data is a frequent task. Sets, in particular, are useful when you need to manage unique elements. A common requirement might involve merging two sets of strings, ensuring that the resultant set contains only unique elements from both sets. This can be useful in scenarios where you need to consolidate data from different sources or perform operations that require a unified dataset without duplicates. In this post, we will demonstrate how to create an Apex method that merges two sets of strings and returns the merged result.
public class LogicalApexClass {
//Creating a method which accepts 2 Sets of String as parameter
public static Set<String> mergeSetsMethod(Set<String> setString1, Set<String> setString2){
//Creating an instance of a Set which will hold both the sets when they are merged
Set<String> mergedSet = New Set<String>();
//Making sure setString1 and setString1 Sets are not empty
if(!setString1.isEmpty() && !setString2.isEmpty()){
//addAll(fromSet) == Method of the Set class
//This method adds all of the elements in the "setString1", "setString2" Set to a new instance of "mergedSet" Set that calls the method if they are not already present.
mergedSet.addAll(setString1);
mergedSet.addAll(setString2);
}
System.debug('this is mergedSet==='+mergedSet);
return mergedSet;
}
}
Apex# ~ For your reference
SET class in APEX
https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_set.htm