Magician

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 two 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 ~ Create an Apex method that removes duplicate integers from a list and returns a list with unique integers.

When working with lists in Salesforce, you might often encounter scenarios where you need to ensure the uniqueness of elements within a list. This is especially important when dealing with data operations where duplicates could lead to inaccurate results or data integrity issues. One such task involves removing duplicate integers from a list. In this post, we will demonstrate how to create an Apex method that takes a list of integers, removes any duplicate values, and returns a new list containing only unique integers. This method is useful for data cleaning and preparation tasks within your Salesforce environment.

public class LogicalApexClass {

    /* 1st Approach === Using a Set */
    
    //Creating a method which accepts a list of integers as parameter   
    public static List<Integer> uniqueIntegerListMethod(List<Integer> numList){
        
        //Creating an instance of a Set which will be used to make the list unique
        Set<Integer> uniqueSet = New Set<Integer>();
        //Making sure "numList" List is not empty
        if(!numList.isEmpty()){
            /*addAll(fromList) == Method of the List class
             *this method adds all of the elements in the "numList" List to a new instance of "uniqueSet" Set.*/
            uniqueSet.addAll(numList);
        }
        
        
        //Converting a Set to List by passing the "uniqueSet" Set to a new instance of "uniqueList" List of the same data type
        List<Integer> uniqueList = New List<Integer>(uniqueSet);
        System.debug('this is uniqueList==='+uniqueList);
        return uniqueList;
    }
    
    /*================================== OR ==================================== */
    
    /* 2nd Approach === Using a List*/
    
    //Creating a method which accepts a list of integers as parameter
    public static List<Integer> uniqueIntegerListMethod(List<Integer> numList){
        
        //Creating an instance of a List which will hold all the unique integers
        List<Integer> uniqueList = New List<Integer>();
        //Making sure "numList" List is not empty
        if(!numList.isEmpty()){
            //Iterating over "numList" List
            for(Integer i : numList){
                /*Checking if "uniqueList" List contains that particular integer currently being looped over. 
                 *If not then adding it to the "uniqueList" List. 
                 *The second time if the same integer appears in the loop, 
                 *it won't enter the "if" condition because the interger is already present in the "uniqueList" List.*/
                if(!uniqueList.contains(i)){
                    uniqueList.add(i);
                }
            }
        }
        
        System.debug('this is uniqueList==='+uniqueList);
        return uniqueList;
    }
}
Apex

#2 ~ Write an Apex method that takes a list of Opportunity records and returns a map where the key is the Opportunity stage and the value is a list of Opportunity names in that stage.

In Salesforce, Opportunities represent potential revenue and are crucial for sales tracking and forecasting. Often, there is a need to organize and analyze Opportunities based on their stages in the sales process. For instance, you might want to group Opportunities by their stages and list the names of Opportunities within each stage. This can help in creating reports, dashboards, or custom logic for sales performance analysis. In this post, we will demonstrate how to create an Apex method that takes a list of Opportunity records and returns a map where the key is the Opportunity stage and the value is a list of Opportunity names in that stage.

 public class LogicalApexClass {
    
    //Creating a method which accepts a list of opportunities as parameter
    public static Map<String, List<String>> mapOfOppMethod(List<Opportunity> oppList){
    
        /*Creating an instance of a Map which will hold 
         *StageName as key and List of Opportunity Names in that Stage as value*/
        Map<String, List<String>> newOppMap = New Map<String, List<String>>();
        //Making sure "oppList" List is not Empty
        if(!oppList.isEmpty()){
             //Iterating over oppList
             for(Opportunity opp : oppList){
                 String stage = opp.StageName;//Storing the StageName in stage variable
                 String name = opp.Name;//Storing the Name in name variable
                 /*As the loop runs over one opportunity at a time
                  *we will check if the "newOppMap" Map contains the StageName of that particular opportunity.
                  *If the Map doesnot contain the StageName it will go into the "else" condition.
                  *In the "else" part we will create an instance of the list which will hold the Opportunity Name in that Stage.
                  *Now puting the values in the Map where StageName will be the key and List of Name will be value.
                  *Again the loop runs and if it finds the same stage name again then this time it will go into "if" condition.
                  *In "if" part it will add the Names of the opportunity in that Stage.*/
                 if(newOppMap.containsKey(stage)){
                     newOppMap.get(stage).add(name);
                 } else {
                     List<String> nameList = New List<String>();
                     nameList.add(name);
                     newOppMap.put(stage, nameList);
                 }
             }
         }
        
        system.debug('this is newOppMap==='+newOppMap);
        return newOppMap;
    }
}
Apex

#3 ~ Write an Apex method that takes a list of Contact records and returns a map with the Contact’s email as the key and the Contact’s LastName as the value.

In Salesforce, managing Contact records often involves working with various fields such as email addresses and last names. A common requirement might be to create a data structure that allows quick lookup of Contact details based on their email addresses. This can be particularly useful for integration, data validation, or reporting purposes. In this post, we will demonstrate how to create an Apex method that takes a list of Contact records and returns a map where the key is the Contact’s email and the value is the Contact’s LastName. This approach ensures that you can efficiently access a Contact’s last name using their email address as the reference.

public class LogicalApexClass {
    
    //Creating a method which accepts a list of Contacts as parameter
    public static Map<String, String> listToMapOfContactMethod(List<Contact> conList){
    
        /*Creating an instance of a Map which will hold 
         *Contact's Email as key and Contact's LastName as value*/
        Map<String, String> conMap = New Map<String, String>();
        //Making sure "conList" List is not Empty
        if(!conList.isEmpty()){
             //Iterating over conList
             for(Contact c : conList){
                 //Checking if the Email of the currently looped over contact is not Null
                 if(c.Email != Null){
                     //If Email is not null putting the values in the Map
                     conMap.put(c.Email, c.LastName);
                 }
             }
         }
        
        System.debug('this is conMap==='+conMap);
        return conMap;
    }
}
Apex

# ~ For your reference

LIST class in APEX

https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_list.htm