Apex Map Collection Data Type: The Powerful Tool Every Salesforce Developer Must Know

Nude Neutral Minimalist Serif Content Creator YouTube Thumbnail

Types of collection data types available in Salesforce

Salesforce offers several collection data types that are commonly used in Apex programming. These include:

  • Lists: A List is an ordered collection of elements that can be of any data type, such as primitive types, sObjects, or custom Apex classes. Lists are indexed and allow duplicate values.
  • Sets: A Set is an unordered collection of elements that does not allow duplicate values. Sets can be of any data type, and are often used for filtering and removing duplicates from Lists.
  • Maps: A Map is a collection of key-value pairs, where each key is unique and associated with a value of any data type. Maps are often used for efficient lookup and retrieval of data based on a specific key.

The advantages of Apex maps over other collection data types in Salesforce

Apex Map is a powerful data type in Salesforce that has several benefits over other collection data types such as Lists and Sets. Here are some of the benefits:

  • Key-value pairs – Apex Map uses a key-value pair structure, which allows for efficient lookup and retrieval of data. This is particularly useful when working with large data sets, as it allows for quick access to specific values based on their associated key.
  • Easy data manipulation – Apex Map provides a variety of methods for manipulating and working with data, such as put(), get(), containsKey(), and keySet(). These methods make it easy to add, retrieve, and modify data in a Map.
  • Avoiding nested loops – By using a Map to store related data, it is possible to avoid nested loops in your code, which can greatly improve performance and reduce the risk of hitting governor limits.
  • Grouping and aggregating data – Apex Map provides functionality for grouping and aggregating data based on a specific key, which can be useful for generating reports or performing calculations.
  • Flexibility – Apex Map is a flexible data type that can store a wide range of data types, including primitive types, custom objects, and even other Maps. This allows for a high degree of customization and adaptability in your code.

Apex Map Collection Methods Apex Map collection comes with a set of built-in methods that developers can use to manipulate and retrieve data. Some of the commonly used methods include:

  1. put(key, value): Adds a new key-value pair to the Map collection.
  2. get(key): Retrieves the value associated with the specified key.
  3. containsKey(key): Checks if the Map collection contains a specific key.
  4. keySet(): Returns a set of all the keys in the Map collection.
  5. values(): Returns a list of all the values in the Map collection.
  6. isEmpty() : Checks if the Map collection is empty.
  7. size() : Map key-value pairs are returned as a count.
  8. toString() : gives the string representation of the map.
  9. remove(key) : Removes the mapping for the specified key from the map, if present, and returns the corresponding value.

Explanation of Map methods in Apex programming with examples

  1. Map<Id, SObject>: This Map type allows you to store SObjects by their Ids.Creates a new instance of the Map class and fills it with the sObject records passed in. In the keys, the sObject IDs are populated and in the values, the sObjects are populated.

Example:

List<Account> accList = [select Id,Name from Account];
Map<Id, Account> m = new Map<Id, Account>(accList);
  1. Map<Integer, SObject>: This Map type allows you to store SObjects by an integer key.

Example:

List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];

Map<Integer, Account> accountMap = new Map<Integer, Account>();
for(Integer i=0; i<accounts.size(); i++){
    accountMap.put(i, accounts[i]);
}
system.debug(' This method returns a set of all the keys in the Map'+accountMap.keySet());
system.debug(' This method returns a list of all the values in the Map'+accountMap.values());
  1. Map<SObject, List<SObject>> OR Map<Id, List<SObject>>: This Map type allows you to store a list of related SObjects by their parent SObject or Ids.

Example using Map<SObject, List<SObject>> :

List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
List<Contact> contacts = [SELECT Id, AccountId, FirstName, LastName FROM Contact WHERE AccountId IN :accounts];

Map<Account, List<Contact>> accountContactMap = new Map<Account, List<Contact>>();
for(Account acc : accounts){
    List<Contact> accContacts = new List<Contact>();
    for(Contact con : contacts){
        if(con.AccountId == acc.Id){
            accContacts.add(con);
        }
    }
    accountContactMap.put(acc, accContacts);
}

Example using Map<Id, List<SObject>> :

List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
List<Contact> contacts = [SELECT Id, AccountId, FirstName, LastName FROM Contact WHERE AccountId IN :accounts];

Map<Id, List<SObject>> accountContactMap = new Map<Id, List<SObject>>();
for(Account acc : accounts){
    List<SObject> accContacts = new List<SObject>();
    for(Contact con : contacts){
        if(con.AccountId == acc.Id){
            accContacts.add(con);
        }
    }
    accountContactMap.put(acc.Id, accContacts);
}

The use of map can be helpful in avoiding nested for loops

This can be particularly useful when you need to perform operations on related records, as you can use a Map to quickly retrieve the related records and avoid multiple nested loops.
Let’s say you have two custom objects in Salesforce: Order__c and Order_Item__c. Each Order__c can have multiple Order_Item__c records related to it. You want to update a field on each Order_Item__c record based on a value from its parent Order__c record.
Without using a Map (Nested for loops)

List<Order__c> orders = [SELECT Id, Name, Order_Field__c FROM Order__c];
List<Order_Item__c> orderItems = [SELECT Id, Order__c, Name, Value__c FROM Order_Item__c];

for(Order__c order : orders) {
    for(Order_Item__c item : orderItems) {
        if(item.Order__c == order.Id) {
            item.Value__c = order.Order_Field__c;
        }
    }
}

update orderItems;

With using a Map (avoiding nested for loops)

List<Order_Item__c> orderItems = [SELECT Id, Order__c, Name, Value__c FROM Order_Item__c];
Map<Id, Order__c> orderMap = new Map<Id, Order__c>([SELECT Id, Name, Order_Field__c FROM Order__c WHERE Id IN (SELECT Order__c FROM Order_Item__c)]);

for(Order_Item__c item : orderItems) {
    Order__c parentOrder = orderMap.get(item.Order__c);
    if(parentOrder != null) {
        item.Value__c = parentOrder.Order_Field__c;
    }
}

update orderItems;

Note : using the above example you can try to update contact phone field from account phone value. In case of any difficulty, please comment below.

Use Cases :

  • Retrieving related records – Maps can be used to efficiently retrieve related records without using nested loops. For example, you can use a Map to store a list of related child records for each parent record, and then iterate over the parent records to access their corresponding child records.
  • Grouping data – Maps can be used to group data by a specific field value. For example, you can use a Map to group leads by their source, or to group opportunities by their stage.
  • Removing duplicates – Maps can be used to remove duplicates from a list of records based on a specific field value. For example, you can use a Map to remove duplicate leads based on their email address.
  • Storing configuration settings – Maps can be used to store configuration settings for your application, such as the values of custom settings or the contents of a custom metadata type.
  • Caching data – Maps can be used to cache frequently accessed data to improve performance. For example, you can use a Map to cache the results of a complex query or calculation, and then retrieve the cached data instead of re-calculating it each time.

While using a map, we should avoid making the following mistakes

  1. Not checking if a key exists before accessing its value.
  2. Overwriting existing values.
  3. Not initializing a Map.
  4. Using non-unique keys.
  5. Not understanding Map behavior.
  6. Forgetting to check for null values.
  7. Using mutable keys.
  8. Using too many Map collections.

3 thoughts on “Apex Map Collection Data Type: The Powerful Tool Every Salesforce Developer Must Know

Leave a Reply

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