Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!

Earn a Salesforce AI Certification by IIT + 12-Week Internship Secure Your Spot Today!
Unlocking the Power of Collections in Salesforce

Unlocking the Power of Collections in Salesforce

Are you looking for a way to efficiently handle and process large sets of data in Salesforce? Look no further than Collections! Collections are an important OOP(object-oriented programming) concept that is also available in Apex that can improve the performance and simplicity of your code while enhancing your data processing capabilities.

In this blog post, we will delve into the various collection types offered by Salesforce, such as List, Set, and Map. We will explore their distinct characteristics and discuss how they can be effectively utilized in Salesforce development. We will also compare each Collection type and provide real-world examples of how Collections can be used to retrieve, filter, and group data.

What are Collections in Salesforce?

Collections in Salesforce are like the tidy-up crew for your data. Just as a neat and organized space makes it easier to find what you need, Collections help you organize and manipulate data in a more efficient and intuitive way. In simple terms, Collections are a way to group related data together. They are very useful for bulk DML operations to manage governor limits.

Types of Collections in Salesforce

Salesforce offers three main types of Collections: List, Set, and Map. Each type has its own unique structure and functionality, but they all share a common purpose; to make it easier for developers to handle data.

  • List: A List is an ordered collection of elements. You can think of it like a grocery list – each item is numbered and has a specific place in the List. Lists are beneficial when preserving the data order or accessing elements based on their position is necessary. 
  • Set: Sets are unordered collections that store only unique elements. In other words, it’s like a drawer full of different socks – each pair is unique, but there’s no specific order to them. Sets are useful when you need to ensure that your data is distinct and when you don’t need to maintain order.
  • Map: A Map is a collection of key-value pairs. It’s like a dictionary – each word (key) has a corresponding definition (value). When you need to seek values based on their associated keys, maps come in handy.

salesforce certification courses for your team

1. List Collection

In Salesforce, a List Collection is a useful Apex programming language feature that allows developers to store and modify a sequence of objects of the same data type. It is a powerful feature of the Apex programming language that allows developers to perform various operations on the List, such as sorting, searching, filtering, and iterating.

List Syntax and Structure

The syntax of List in Apex is similar to that of an array in other programming languages. The declaration of a List starts with the data type of the elements, followed by the name of the List, and then the opening and closing square brackets.

For example, the following code declares a List of type String:

List<String> myStringList = new List<String>();

Basic Operations on List

There are various operations that can be performed on List in Salesforce. Some of the basic operations include:

  • Adding elements to the List
  • Accessing elements from the List
  • Updating elements in the List
  • Removing elements from the List
  • Sorting the List
  • Searching for elements in the List
  • Filtering the List

Example of List Collection

Let’s say we want to create a List of contacts in Salesforce. We can do this by creating a new List of type Contact and adding the contacts to it as follows:

List<Contact> myContactList = new List<Contact>(); myContactList.add(new Contact(FirstName=’John’, LastName=’Doe’, Email=’johndoe@example.com’)); myContactList.add(new Contact(FirstName=’Jane’, LastName=’Doe’, Email=’janedoe@example.com’));

Methods Used in List Collection

Common Methods Used in List

There are several methods that can be used in List in Salesforce. Some of the common methods include:

  • add(): adds an element to the end of the List
  • size(): returns the number of elements in the List
  • get(): returns the element at the specified index
  • set(): replaces the element at the specified index with a new element
  • remove(): removes the element at the specified index from the List
  • sort(): sorts the elements in the List
Examples of Methods Used in List

Let’s say we want to update the email of the second contact in our List. We can do this by using the set() method as follows:

myContactList.set(1, new Contact(FirstName=’Jane’, LastName=’Doe’, Email=’newemail@example.com’));

We can also remove the first contact from the List using the remove() method as follows:

myContactList.remove(0);

Finally, we can sort the List by the last name of the contacts using the sort() method as follows:

myContactList.sort((c1, c2) => c1.LastName.compareTo(c2.LastName));

List Collection is a powerful feature of the Apex programming language that allows developers to store and manipulate a collection of elements of the same data type in a sequential order. By understanding the syntax and structure of List, basic operations, and methods used in List Collection, developers can create powerful applications in Salesforce.

salesforce platform developer 1 bootcamp

2. Set Collection

In Salesforce, a Set Collection is a data structure that stores a collection of unique elements of the same data type. Unlike List Collection, Sets do not maintain a specific order and are primarily used to check for the existence of an element in the collection.

Set Syntax and Structure

The syntax of Set in Apex is similar to that of a List, with the only difference being the use of curly braces instead of square brackets. The declaration of a Set starts with the data type of the elements followed by the name of the Set.

For example, the following code declares a Set of type Integer:

Set<Integer> myIntegerSet = new Set<Integer>();

Basic Operations on Set

There are various operations that can be performed on Set in Salesforce. Some of the basic operations include:

  • Adding elements to the Set
  • Accessing elements from the Set
  • Updating elements in the Set
  • Removing elements from the Set
  • Checking if an element exists in the Set

Example of Set Collection

Let’s say we want to create a Set of product codes in Salesforce. We can do this by creating a new Set of type String and adding the product codes to it as follows:

Set<String> myProductCodeSet = new Set<String>{‘P1001’, ‘P1002’, ‘P1003’};

Methods Used in Set Collection

Common Methods Used in Set

There are several methods that can be used in Set in Salesforce. Some of the common methods include:

  • add(): adds an element to the Set
  • size(): returns the number of elements in the Set
  • contains(): checks if an element exists in the Set
  • remove(): removes the element from the Set
Examples of Methods Used in Set

Let’s say we want to add a new product code to our Set. We can do this by using the add() method as follows:

myProductCodeSet.add(‘P1004’);

We can also check if a specific product code exists in the Set using the contains() method as follows:

if (myProductCodeSet.contains(‘P1002’)) { System.debug(‘Product code P1002 exists in the Set.’); }

Finally, we can remove a product code from the Set using the remove() method as follows:

myProductCodeSet.remove(‘P1003’);

So, Set Collection is a data structure that stores a collection of unique elements of the same data type in Salesforce. By understanding the syntax and structure of Set, basic operations, and methods used in Set Collection, developers can create powerful applications that require unique values or fast lookups.

3. Map Collection

In Salesforce, a Map Collection is a data structure that stores a collection of key-value pairs, where each key maps to a value. Maps are useful in situations where we need to access values based on a specific key.

Map Syntax and Structure

The syntax of Map in Apex is similar to that of a List or Set, with the only difference being the use of angle brackets and a comma to separate the key and value types. The declaration of a Map starts with the data type of the key, followed by the data type of the value, and then the name of the Map.

For example, the following code declares a Map of type String for keys and Integer for values:

Map<String, Integer> myMap = new Map<String, Integer>();

Basic Operations on Map

There are various operations that can be performed on Map in Salesforce. Some of the basic operations include:

  • Adding key-value pairs to the Map
  • Accessing values from the Map using keys
  • Updating values in the Map
  • Removing key-value pairs from the Map

Example of Map Collection

Let’s say we want to create a Map of product codes and their prices in Salesforce. We can do this by creating a new Map of type String for keys and Decimal for values and adding the product codes and prices to it as follows:

Map<String, Decimal> myProductCodeMap = new Map<String, Decimal>{ ‘P1001’ => 100.00, ‘P1002’ => 200.00, ‘P1003’ => 300.00 };

Methods Used in Map Collection

Common Methods Used in Map

There are several methods that can be used in Map in Salesforce. Some of the common methods include:

  • put(): adds a key-value pair to the Map
  • get(): returns the value associated with a specific key
  • containsKey(): checks if a specific key exists in the Map
  • remove(): removes a key-value pair from the Map
Examples of Methods Used in Map

Let’s say we want to add a new product code and price to our Map. We can do this by using the put() method as follows:

myProductCodeMap.put(‘P1004’, 400.00);

We can also retrieve the price of a specific product code from the Map using the get() method as follows:

Decimal price = myProductCodeMap.get(‘P1002’); System.debug(‘Price of product code P1002 is: ‘ + price);

If we want to check if a specific product code exists in the Map, we can use the containsKey() method as follows:

if (myProductCodeMap.containsKey(‘P1003’)) { System.debug(‘Product code P1003 exists in the Map.’); }

Finally, we can remove a specific key-value pair from the Map using the remove() method as follows:

myProductCodeMap.remove(‘P1002’);

So, Map Collection is a data structure that stores a collection of key-value pairs in Salesforce. By understanding the syntax and structure of Map, basic operations, and methods used in Map Collection, developers can create powerful applications that require key-value mappings or fast lookups.

Comparison of Collections in Salesforce

Collection TypeProperties and FeaturesUse Cases
List
  • Ordered collection of elements
  • Allows duplicate elements
  • Elements accessed by index
  • When order of elements matters
  • When duplicate elements need to be retained
Set
  • Unordered collection of elements
  • Does not allow duplicate elements
  • Elements accessed by iterating over the set
  • When uniqueness of elements is important
  • When order of elements does not matter
Map
  • Collection of key-value pairs
  • Keys are unique and used to access values
  • No order of elements
  • When accessing values by a unique identifier
  • When mapping a key to a value
  • When duplicate keys need to be prevented

Factors to Consider When Selecting a Collection Type

When selecting a Collection type in Salesforce, developers should consider the following factors:

  • Data Requirements: Does the application require ordered data or unique data?
  • Data Size: Will the Collection be small or large? Lists can be inefficient for large datasets, whereas Sets and Maps can be more efficient.
  • Performance: Will the Collection require frequent lookups or frequent additions/removals? Sets and Maps can be faster for lookups, whereas Lists may be more efficient for adding and removing elements.
  • Complexity: Will the application require complex data structures, such as nested or multidimensional Collections? Maps can be useful for more complex data structures.
  • Integration with Other Code: Will the Collection need to integrate with existing code? The choice of Collection type may depend on the existing codebase and how the data is being used.
 

Summing Up

In conclusion, Collections are an essential tool for developers to efficiently handle and process data in Salesforce. They offer a powerful and flexible way to group related data together, and can significantly improve the performance and simplicity of your code.

By understanding the unique features and capabilities of each Collection type, developers can choose the best option to suit their specific needs. Whether you need to maintain order, ensure data uniqueness, or look up values based on associated keys, Collections have got you covered.

So, if you want to elevate your Salesforce development skills to new heights, make it a priority to become proficient in working with Collections. Mastering the utilization of Lists, Sets, and Maps will empower you to handle data more efficiently and unlock the full potential of your Salesforce solutions. With their help, you can organize and manipulate data in a more efficient and intuitive way, leading to better performance and improved user experience.

Get certified as a Salesforce Developer with saasguru by enrolling in our Salesforce Platform Developer 1 training with capstone projects.

You can also check out our self-learn Salesforce Developer Course: Platform Developer 1 Certification – get a personalized study plan, free mock exams, quizzes, flashcards and much more.

If you want to explore more, sign up with the saasguru community on Slack and interact with seasoned Salesforce professionals. It puts a ton of valuable resources and expert insights, making learning super convenient and hassle-free from your smartphone.

Frequently Asked Questions (FAQs)

1. What is a Collection in Salesforce?

In Salesforce, a Collection is a data structure that allows you to store and manipulate groups of objects. Collections play a vital role in Salesforce’s Apex programming language, enabling developers to handle sets of data efficiently and perform bulk operations while adhering to governor limits.

Salesforce offers three main types of Collections:

  • List: An ordered collection of elements, akin to an array, where each element is identified by its index.
  • Set: An unordered collection of unique elements, useful for storing non-duplicate values without any specific ordering.
  • Map: A collection that stores data in key-value pairs, similar to a dictionary, where each unique key maps to a single value. These Collections help in organizing data logically and can significantly enhance the performance of Apex code.

2. How to Use Collection in Salesforce Flow?

Collections in Salesforce Flow can be used to gather and process multiple records at once. Here’s how you can use them:

  • Define Collection Variables: In your Flow, define a collection variable (List, Set, or Map) based on your requirement.
  • Gather Data into Collections: Use ‘Get Records’ elements in Flow to query records and store them into your collection variable. For instance, you can store a list of contacts meeting specific criteria in a List collection.
  • Loop through Collections: Utilize ‘Loop’ elements to iterate over the collection and perform actions on each record. For example, you can loop through the list of contacts and update each record.
  • Use Collections in Decisions: You can use collection variables in ‘Decision’ elements to guide the flow based on the data stored in the collection. Implementing Collections in Salesforce Flow allows for more dynamic and powerful data processing, especially when dealing with multiple records.

3. How Do I Create a Collection in Salesforce?

Creating a collection in Salesforce, particularly in Apex, involves a few simple steps:

  • List: To create a List, declare it with a specific data type. For example: List<String> myStringList = new List<String>();
  • Set: To create a Set, declare it with its data type. For example: Set<String> myStringSet = new Set<String>();
  • Map: To create a Map, specify both key and value data types. For example: Map<String, Integer> myMap = new Map<String, Integer>(); After declaring a collection, you can add elements to it using methods like add() for Lists and Sets, and put() for Maps.

These collections can then be utilized in various Apex operations, such as looping, sorting, and data manipulation.

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Mass Assign User Permission Set in Salesforce

Learn how to efficiently mass assign user permission sets in Salesforce using tools like Data Loader. Save time and ensure accuracy. Read now!

How to Clone a FlexCard in Salesforce

Learn how to clone a FlexCard in Salesforce with this step-by-step guide. Simplify customization and boost efficiency effortlessly!

Salesforce Introduces Agentforce 2.0: Redefining How Work Gets Done

Salesforce introduces Agentforce 2.0, the AI platform transforming digital labor with autonomous agents and seamless workflows. Read now!