
Collections in Apex Programming of Salesforce

Tables of Contents
A collection is a type of variable in apex that can store multiple items.Collections In Apex can be List, Set, or Map.
Lists
A list is an ordered collection of elements characterized by their indexes. A list element can be of any type, including primitive types, collections, sObjects, user-defined types, and Apex types. List in apex is similar to the array in Java. Each list index begins with 0. The list can store duplicate and null values.
Following are the methods supported by List.
Read more: Latest Salesforce interview questions and answers.
Add()
The add()
method is used to add an element to a collection, such as a list or a set. It is commonly used to build up a collection by adding individual elements one at a time.
List numbers = new List();
numbers.add(5); // Adds 5 to the list
System.debug(numbers); // Output: [5]
In this example, the add()
method is used to add the integer 5 to a list of integers called numbers
. After adding the element, the list contains a single element, which is 5.
Read more: String methods in Salesforce apex
Remove()
The remove()
method is used to remove an element from a collection at a specified index. It is often used to modify a collection by removing elements that are no longer needed.
List<String> fruits = new List<String>{'Apple', 'Banana', 'Orange'};
fruits.remove(1);
In this example, the remove()
method is used to remove the element at index 1 from a list of strings called fruits
. After removing the element, the list contains two elements: ‘Apple’ and ‘Orange’.
Clear()
The clear()
method is used to remove all elements from a collection, effectively emptying it. It is commonly used to reset a collection to its initial empty state.
List<String> colors = new List<String>{'Red', 'Green', 'Blue'};
colors.clear();
In this example, the clear()
method is used to remove all elements from a list of strings called colors
. After clearing the list, it contains no elements.
Clone()
The clone()
method is used to create a new instance of a collection that contains all the elements of the original collection. It is often used to create a copy of a collection that can be modified independently of the original.
List<Integer> originalList = new List<Integer>{1, 2, 3};
List<Integer> clonedList = originalList.clone(); // Clones the list
System.debug(clonedList); // Output: [1, 2, 3]
In this example, the clone()
method is used to create a new list called clonedList
that contains the same elements as the originalList
. The cloned list can be modified without affecting the original list.
Checkout: DML statements in Salesforce
Size()
The size()
method is used to determine the number of elements in a collection. It is commonly used to check the size of a collection before performing operations that depend on the number of elements.
List<String> animals = new List<String>{'Cat', 'Dog', 'Bird'};
Integer listSize = animals.size(); // Gets the size of the list
System.debug(listSize); // Output: 3
In this example, the size()
method is used to determine the number of elements in a list of strings called animals
. The list contains three elements, so the size is 3.
Read more: SOQL Query in Salesforce
Equals()
The equals()
method is used to compare two objects for equality. It is often used to compare strings, but it can be used with any type of object that implements the equals()
method.
String str1 = 'Hello';
String str2 = 'Hello';
Boolean isEqual = str1.equals(str2); // Compares the two strings
System.debug(isEqual); // Output: true
In this example, the equals()
method is used to compare two strings, str1
and str2
. Since both strings contain the same sequence of characters, the method returns true
, indicating that they are equal.
Sets
Sets are a collection of unordered elements that are not duplicated. There are several types of elements in the set — primitives, collections, sObjects, user-defined types, and built-in Apex types.
Following are the methods supported by sets:
Add()
The add()
method in Apex is used to add an element to a set. Sets are collections that store unique elements, so if you try to add a duplicate element, it won’t be added to the set. This method is useful when you want to build a collection of distinct items.
Set<String> fruits = new Set<String>();
fruits.add('Apple'); // Adds 'Apple' to the set
System.debug(fruits); // Output: {Apple}
In this example, the add()
method is used to add the string ‘Apple’ to a set called fruits
. After adding ‘Apple’, the set contains one element.
Read more: Interfaces in Salesforce
Remove()
The remove()
method is used to remove a specific element from a set. If the element is present in the set, it is removed, and the set is updated. This method is handy when you want to eliminate an item from a collection of unique elements.
Set<String> colors = new Set<String>{'Red', 'Green', 'Blue'};
colors.remove('Green'); // Removes 'Green' from the set
System.debug(colors); // Output: {Red, Blue}
In this example, the remove()
method is used to remove the string ‘Green’ from a set called colors
. After removing ‘Green’, the set contains two elements, ‘Red’ and ‘Blue’.
Size()
The size()
method is used to get the number of elements in a set. It tells you how many unique items are stored in the set. This method is useful when you need to know the size of your collection.
Set<Integer> numbers = new Set<Integer>{1, 2, 3, 4, 5};
Integer setSize = numbers.size(); // Gets the size of the set
System.debug(setSize); // Output: 5
In this example, the size()
method is used to find out how many elements are in a set called numbers
. The set contains five elements, so the size is 5.
Contain()
The contains()
method is used to check if a set contains a specific element. It returns true
if the element is in the set and false
if it’s not. This method is helpful when you want to know if an item is part of a collection.
Set<String> animals = new Set<String>{'Cat', 'Dog', 'Bird'};
Boolean containsDog = animals.contains('Dog'); // Checks if 'Dog' is in the set
System.debug(containsDog); // Output: true
In this example, the contains()
method is used to check if the set animals
contains the string ‘Dog’. The method returns true
because ‘Dog’ is in the set.
Read more: database methods in Salesforce
Equals()
The equals()
method is used to compare two sets to see if they contain the same elements. It returns true
if both sets have the same elements, regardless of the order, and false
if they don’t. This method is useful when you want to check if two collections are identical.
Set<String> set1 = new Set<String>{'A', 'B', 'C'};
Set<String> set2 = new Set<String>{'A', 'B', 'C'};
Boolean isEqual = set1.equals(set2); // Compares the two sets
System.debug(isEqual); // Output: true
In this example, the equals()
method is used to compare two sets, set1
and set2
. Both sets contain the same elements, so the method returns true
, indicating that they are equal.
Read more: Loops in Salesforce Apex
Maps
In Salesforce Apex, a Map is a collection that stores data in key-value pairs. Each key is unique and is used to access its corresponding value. Think of it like a dictionary, where you look up a word (the key) to find its meaning (the value). Maps are useful for organizing data in a way that makes it easy to find and access specific items. They are commonly used to store and manage relationships between objects or to quickly access data based on a unique identifier.
Following are the methods supported by Maps in Apex:
clear()
The clear()
method is used to remove all the entries from a map. This method is handy when you want to reset a map to an empty state, removing all the key-value pairs it contains. After using clear()
, the map will be empty, and its size will be zero. This method does not return any value.
Map<String, Integer> scores = new Map<String, Integer>{'Alice' => 90, 'Bob' => 85};
scores.clear(); // Clears all entries from the map
System.debug(scores); // Output: {}
In this example, we start with a map called scores
that contains two entries, mapping names to scores. The clear()
method is called on the scores
map, which removes all the entries. After clearing, the map is empty, as shown by the output {}
, which represents an empty map.
Read more: Methods – Salesforce Apex
clone()
The clone()
method is used to create a copy of a map. When you clone a map, you get a new map that contains all the same key-value pairs as the original, but it’s a separate object. This means that changes made to the cloned map won’t affect the original map, and vice versa. Cloning is useful when you want to work with a copy of a map without altering the original data.
Map<String, String> originalMap = new Map<String, String>{'color' => 'blue', 'shape' => 'circle'};
Map<String, String> clonedMap = originalMap.clone(); // Clones the map
System.debug(clonedMap); // Output: {color=blue, shape=circle}
In this example, we have an originalMap
that maps characteristics of an object to their values, like 'color' => 'blue'
and 'shape' => 'circle'
. We use the clone()
method to create a clonedMap
that is an exact copy of the originalMap
. The output shows that the clonedMap
has the same entries as the originalMap
. Any changes made to clonedMap
will not affect originalMap
and vice versa, making it safe to modify the clone without altering the original data.
Read more: Classes – Salesforce Apex
containsKey(key)
The containsKey(key)
method is used to check if a map contains a specific key. It returns true
if the key is found in the map and false
if it is not. This method is helpful when you want to know whether a certain key exists in the map before trying to access its value. It ensures that you don’t encounter errors by trying to get a value for a key that doesn’t exist.
Map<Integer, String> days = new Map<Integer, String>{1 => 'Monday', 2 => 'Tuesday'};
Boolean hasKey = days.containsKey(1); // Checks if the key 1 exists in the map
System.debug(hasKey); // Output: true
In this example, we have a map called days
that maps numbers to days of the week, with 1
representing ‘Monday’ and 2
representing ‘Tuesday’. We use the containsKey(key)
method to check if the key 1
exists in the map. The method returns true
because the key 1
is present in the map, indicating that ‘Monday’ is a value in the map. This is useful for avoiding errors when trying to access a value that might not be present in the map.
Read more: Objects – Salesforce Apex
deepClone()
The deepClone()
method is used to create a deep copy of a map. Unlike the regular clone()
method, deepClone()
also creates copies of the objects that are values in the map. This is useful when you want to create a completely independent copy of a map with complex objects, ensuring that changes to the cloned map or its objects do not affect the original map or its objects.
Map<String, List<String>> originalMap = new Map<String, List<String>>{'fruits' => new List<String>{'apple', 'banana'}};
Map<String, List<String>> deepClonedMap = originalMap.deepClone(); // Deep clones the map
System.debug(deepClonedMap); // Output: {fruits=(apple, banana)}
In this example, we have an originalMap
that maps a category ‘fruits’ to a list of fruit names. We use the deepClone()
method to create a deepClonedMap
that is a deep copy of the originalMap
. This means that the list of fruits in the cloned map is a separate copy from the list in the original map. Any changes made to the list in the deepClonedMap
will not affect the list in the originalMap
, and vice versa. This is particularly useful when working with complex data structures where you need to ensure that the original data remains unchanged.
Read more: SOQL in Salesforce
equals(map2)
The equals(map2)
method is used to compare two maps for equality. It returns true
if both maps contain the same key-value pairs, regardless of the order in which they appear. This method is useful when you want to check if two maps represent the same data. It’s important to note that both the keys and the values must be equal for the maps to be considered equal.
Map<String, Integer> map1 = new Map<String, Integer>{'a' => 1, 'b' => 2};
Map<String, Integer> map2 = new Map<String, Integer>{'a' => 1, 'b' => 2};
Boolean isEqual = map1.equals(map2); // Compares map1 and map2
System.debug(isEqual); // Output: true
In this example, we have two maps, map1
and map2
, that both map letters to numbers. We use the equals(map2)
method to compare these two maps. The method returns true
because both maps contain the same key-value pairs, even though the order of the pairs might be different. This shows that the two maps represent the same data, making them equal in the context of this method.
Readmore: Database methods in Salesforce Apex
get(key)
The get(key)
method is used to retrieve the value associated with a specific key in a map. If the key exists in the map, the method returns its corresponding value. If the key is not found, it returns null
. This method is essential for accessing data in a map, as it allows you to get the value of a particular key.
Map<String, String> capitals = new Map<String, String>{'USA' => 'Washington, D.C.', 'India' => 'New Delhi'};
String capitalOfIndia = capitals.get('India'); // Gets the value associated with the key 'India'
System.debug(capitalOfIndia); // Output: New Delhi
In this example, we have a map called capitals
that maps country names to their capital cities. We use the get(key)
method to retrieve the capital of India by passing the key 'India'
to the method. The method returns the value 'New Delhi'
, which is the capital city associated with the key 'India'
. This demonstrates how you can use the get(key)
method to access specific information in a map based on its key.
Readmore: SOSL Query in Salesforce Apex
getSObjectType()
The getSObjectType()
method is used to retrieve the Salesforce Object Type (SObjectType) of the records stored in a map. This method is particularly useful when working with maps that contain Salesforce records (sObjects), as it allows you to determine the type of sObject the map is handling. It helps ensure that you are working with the correct type of records in your Apex code.
Map<Id, Account> accountsMap = new Map<Id, Account>();
Schema.SObjectType objectType = accountsMap.getSObjectType(); // Gets the SObject type of the map
System.debug(objectType); // Output: Account
In this example, we have a map called accountsMap
that is designed to store Account
records, with their Salesforce record IDs as keys. We use the getSObjectType()
method to retrieve the SObjectType of the records in the map. The method returns Account
, indicating that the map is intended to hold Account
records. This information can be useful for validating that the map contains the expected type of sObject.
Read more: security in salesforce
isEmpty()
The isEmpty()
method is used to check if a map is empty, meaning it contains no key-value pairs. It returns true
if the map is empty and false
if it contains at least one entry. This method is helpful when you want to ensure that a map has data before performing operations on it, preventing errors that might occur when working with an empty map.
Map<String, Integer> map = new Map<String, Integer>();
Boolean isEmpty = map.isEmpty(); // Checks if the map is empty
System.debug(isEmpty); // Output: true
In this example, we have a map called map
that is initially empty. We use the isEmpty()
method to check if the map contains any entries. The method returns true
, indicating that the map is indeed empty. This check can be useful in scenarios where you need to perform different actions based on whether the map has data or not.
Readmore: Loops in Salesforce Apex
keySet()
The keySet()
method is used to retrieve all the keys from a map as a set. This is useful when you need to iterate over the keys of a map or perform operations based on the keys. The returned set contains all the unique keys from the map, allowing you to access each key without worrying about duplicates.
Map<String, Double> prices = new Map<String, Double>{'apple' => 1.99, 'banana' => 0.99};
Set<String> keys = prices.keySet(); // Gets the set of keys from the map
System.debug(keys); // Output: {apple, banana}
In this example, we have a map called prices
that maps fruit names to their prices. We use the keySet()
method to retrieve the keys from the map, which are the names of the fruits. The method returns a set containing 'apple'
and 'banana'
, which are the keys in the prices
map. This set can then be used to iterate over the keys or perform other operations that require access to the keys of the map.
Readmore: Record Types in Salesforce
put(key, value)
The put(key, value)
method is used to add a new key-value pair to a map or update the value of an existing key. If the key already exists in the map, its value is replaced with the new value. If the key does not exist, a new key-value pair is added to the map. This method is fundamental for building and modifying maps in Apex.
Map<Integer, String> map = new Map<Integer, String>();
map.put(1, 'One'); // Adds a key-value pair to the map
System.debug(map); // Output: {1=One}
In this example, we have an empty map called map
. We use the put(key, value)
method to add a new entry to the map, where the key is 1
and the value is 'One'
. After adding the entry, the map contains one key-value pair, as shown in the output. This method is essential for constructing maps and updating their contents.
Readmore: Validation Rules in Salesforce
putAll(fromMap)
The putAll(fromMap)
method is used to add all the key-value pairs from one map to another. If a key in the source map (fromMap
) already exists in the target map, its value is updated to the value from the source map. This method is useful for combining data from two maps or updating a map with values from another map.
Map<String, String> map1 = new Map<String, String>{'a' => 'apple', 'b' => 'banana'};
Map<String, String> map2 = new Map<String, String>{'c' => 'cherry', 'd' => 'date'};
map1.putAll(map2); // Adds all entries from map2 to map1
System.debug(map1); // Output: {a=apple, b=banana, c=cherry, d=date}
In this example, we have two maps, map1
and map2
, each containing different fruit names. We use the putAll(fromMap)
method to add all the entries from map2
to map1
. After the method call, map1
contains all the key-value pairs from both maps, as shown in the output. This demonstrates how you can merge data from two maps using the putAll
method.
Readmore: Page Layouts in Salesforce
putAll(sobjectArray)
The putAll(sobjectArray)
method is used to add records from a list of sObjects to a map. Each record in the list is added to the map with its ID as the key and the record itself as the value. This method is useful for creating a map from a list of records, allowing you to quickly access records by their ID.
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
Map<Id, Account> accountsMap = new Map<Id, Account>();
accountsMap.putAll(accounts); // Adds all accounts from the list to the map
System.debug(accountsMap.keySet()); // Output: Set of account Ids
In this example, we query a list of Account
records and store them in a list called accounts
. We then create an empty map called accountsMap
. Using the putAll(sobjectArray)
method, we add all the records from the accounts
list to the accountsMap
, with their IDs as keys. After the method call, accountsMap
contains all the Account
records from the list, and we can access any record in the map using its ID.
Readmore: Custom Page Layouts in Salesforce
remove(key)
The remove(key)
method is used to delete a key-value pair from a map based on the specified key. If the key exists in the map, its corresponding entry is removed, and the method returns the value associated with the key. If the key is not found, the method returns null
. This method is useful for removing specific entries from a map when you no longer need them or when you want to update the map’s contents.
Map<String, Integer> ages = new Map<String, Integer>{'Alice' => 30, 'Bob' => 25};
Integer removedAge = ages.remove('Alice'); // Removes the entry with key 'Alice'
System.debug(removedAge); // Output: 30
System.debug(ages); // Output: {Bob=25}
In this example, we have a map called ages
that maps names to ages. We use the remove(key)
method to remove the entry for 'Alice'
from the map. The method returns the value 30
, which is the age associated with 'Alice'
, and this entry is removed from the map. After the removal, the map contains only the entry for 'Bob'
. This demonstrates how you can use the remove
method to delete specific entries from a map.
Readmore: Record Types in Salesforce
size()
The size()
method is used to determine the number of key-value pairs in a map. It returns an integer representing the total count of entries in the map. This method is helpful when you need to know how many items are stored in the map, such as when checking if the map is empty or when iterating over its contents.
Map<String, Boolean> flags = new Map<String, Boolean>{'isActive' => true, 'isDeleted' => false};
Integer mapSize = flags.size(); // Gets the number of entries in the map
System.debug(mapSize); // Output: 2
In this example, we have a map called flags
that contains two entries, each mapping a string to a boolean value. We use the size()
method to get the number of entries in the map, which is 2
in this case. This information can be useful for various purposes, such as validating the map’s contents or determining if further processing is needed based on the size of the map.
Readmore: Permission Sets in Salesforce
values()
The values()
method is used to retrieve all the values from a map as a list. This is useful when you need to access just the values of a map without concerning yourself with the keys. The returned list contains all the values from the map in no particular order. This method is helpful for iterating over the values or performing operations on them.
Map<Integer, String> numbers = new Map<Integer, String>{1 => 'One', 2 => 'Two'};
List<String> values = numbers.values(); // Gets the list of values from the map
System.debug(values); // Output: [One, Two]
In this example, we have a map called numbers
that maps integers to their corresponding string representations. We use the values()
method to retrieve all the values from the map, which are the strings 'One'
and 'Two'
. The method returns a list containing these values, allowing us to access or manipulate them separately from the keys of the map. This can be particularly useful when the values are the primary focus of your operation, and the keys are secondary or irrelevant.
At CRS Info Solutions, we provide a well-rounded and dynamic Salesforce course that is designed to help beginners learn the foundational skills necessary to build a successful career in the Salesforce ecosystem. This course equips learners with essential knowledge in Salesforce administration, development, and Lightning Web Components (LWC), making it a comprehensive learning experience. By focusing on these core areas, we ensure that students are well-prepared to manage Salesforce environments, develop custom applications, and implement modern, user-friendly interfaces using LWC.
Throughout the course, we provide daily notes and resources to support the learning process, ensuring that our students have a clear understanding of each concept. We understand the challenges that beginners may face when learning Salesforce, so our program is designed to offer continuous guidance and hands-on experience. In addition to covering the technical aspects, we place special emphasis on interview preparation, helping our learners confidently tackle job interviews by providing real-world scenarios and frequently asked questions.
Moreover, our Salesforce course is designed with certification preparation in mind, giving beginners the tools and knowledge they need to succeed in Salesforce certification exams. We guide students through the certification process step-by-step, ensuring they have a strong understanding of the topics covered in the exams. By the end of the course, learners will not only be ready to achieve their certifications but also be equipped with the practical skills needed to excel in their Salesforce careers.