Collections in Apex (List, Set, and Map) are simply ways to store and manipulate multiple values in a single variable.
In day‑to‑day Salesforce development, you use them all the time in SOQL queries, triggers, and batch jobs to stay within governor limits and keep your code clean.
While working as a Salesforce developer, I was tasked with building an Apex class to automate a customer support process.
The requirement was to retrieve all open cases for a specific customer to see if their status was “New” or “In Progress.”
In Salesforce Apex, we use collections to store multiple records or values. Here, I will explain how to use collections in Salesforce Apex, the different types of collections, and demonstrate methods for manipulating collections.
What is a Collection in Apex?
Collections in Salesforce Apex are used to store multiple records or values in a single variable. Instead of creating many separate variables, collections help you manage data easily and write cleaner code.
They are very useful when working with SOQL queries, loops, and bulk data processing in Salesforce.
There are three main collection types in Apex: List, Set, and Map. A List stores data in an ordered way and allows duplicate values.
A Set stores only unique values and does not allow duplicates. A Map stores data as key–value pairs, where each key is unique and is used to access its related value.
Lists are commonly used when you want to process records one by one in a specific order. Sets are useful for removing duplicate values, such as unique record IDs.
Maps are very powerful when you need fast access to data via a key, such as storing records by their Id for quick lookup.
1. Apex List: Ordered Collection with Duplicates
The list is a collection data type that stores information in a sequential format with an index. The list in Apex is similar to the array in Java. Each list index begins with 0.
The list collection can store duplicate and null values. In Apex, the list size can be increased or decreased at runtime, depending on the number of elements added to it.
A List in Salesforce is an ordered collection of elements that can hold multiple records or values of any data type (such as primitives, objects, or sObjects).
It allows duplicates and maintains the insertion order. Lists are commonly used for bulk operations, such as querying multiple records or performing bulk DML (Data Manipulation Language) actions.
- When we execute the list, we get the output in the order in which we enter the elements.
- The values can be duplicated in the list; the list doesn’t prevent duplicates in the apex collection.
When can we use a List in Apex?
We use a List when:
- We care about the order of items (for example, sorted records).
- We might have duplicates (the same Id or value more than once).
- We want to loop over records in the exact order returned by SOQL.
Syntax of declaring a list collection:
List <Datatype> myList = new <Datatype>();
List<Integer>myList = new List<Integer>{1,8,6,4,6,9}; //declare and add values to list.In the following Apex code, I first declare a list variable and then use the add() method to add values to the list. As you display the list, you will see the added elements.
List<Integer>myList = new List<Integer>();
myList.add (5);
myList.add (3);
myList.add (9);
myList.add (2);
myList.add (3);
system.debug( 'Collection of List is: ' +myList);As you execute the code, you can see that an integer has been added to the list, and it also displays duplicate values.

Common List methods in Apex (with examples)
Here are the List methods I actually use day to day.
1. add() – add elements to the list
textList<String> fruits = new List<String>();
fruits.add('Apple');
fruits.add('Banana');
fruits.add('Mango');
System.debug(fruits); // (Apple, Banana, Mango)
Add at a specific index:
textfruits.add(1, 'Orange');
System.debug(fruits); // (Apple, Orange, Banana, Mango)
2. get() and set() – read and update by index
textString firstFruit = fruits.get(0);
System.debug(firstFruit); // Apple
fruits.set(0, 'Grapes');
System.debug(fruits); // (Grapes, Orange, Banana, Mango)
3. size() – number of elements
textInteger count = fruits.size();
System.debug('Count: ' + count);
I always use size() in loops or before accessing an index to avoid out‑of‑bounds errors.
4. isEmpty() – quick check
textif (!fruits.isEmpty()) {
System.debug('We have some fruits');
}
5. remove() / clear() – delete elements
textfruits.remove(1); // remove element at index 1
System.debug(fruits);
fruits.clear(); // remove all elements
System.debug(fruits); // ()
6. contains() – check if value exists
textList<String> colors = new List<String>{'Red','Green','Blue'};
Boolean hasRed = colors.contains('Red');
System.debug(hasRed); // true
7. sort() – sort ascending
textList<Integer> scores = new List<Integer>{40, 10, 25, 10};
scores.sort();
System.debug(scores); // (10, 10, 25, 40)
For a descending sort, I usually sort in ascending order and then loop from the end, or copy into another list as needed.
2. Set Collection in Salesforce Apex
Set collections are similar to lists, but some properties of sets differ from those of lists. The elements in the set collection are stored in an unordered format.
The values we store in the set should be unique, as it does not allow duplicates.
- When we execute the set, we get the values in ascending order as an output.
- If we enter duplicate values, the set removes them and displays only unique values, thereby preventing duplicates in the Apex collection.
I use a Set when:
- I just care whether a value exists.
- I need to remove duplicates (Ids, emails, etc.).
- I need fast lookup of “is this value in the group?”.
Common use cases:
- Collecting Ids from trigger records.
- Building a unique list of field values (like unique email domains).
- Using IN:someSet in SOQL queries.
Syntax of declaring a Set collection in Apex:
Set<Datatype> mySet = new Set<Datatype>();
In the Apex code below, I showed you how to declare a set collection in Salesforce Apex.
Set<Integer>SetInt= new Set<Integer>{4,6,3,2,7,2,8};
system.debug(' Values in Set are: ' +SetInt);
Set<String>SetString= new Set<String>{'Jira', 'Apex', 'MongoDB', 'VisualForce', 'LWC', 'Apex'};
system.debug(' Values in Set are: ' +SetString);As you execute the code above, you will see the set remove duplicate values and display them only once. It also displays the set of values in ascending order.

Common Set Methods in Apex (with examples)
1. add() – insert elements
textSet<String> tags = new Set<String>();
tags.add('New');
tags.add('VIP');
tags.add('New'); // ignored, already exists
System.debug(tags); // (New, VIP)
2. contains() – check if a value exists
textBoolean isVip = tags.contains('VIP');
System.debug(isVip); // true
This is one of the main reasons I use a Set in validation or decision logic.
3. size() and isEmpty()
textInteger count = tags.size();
Boolean empty = tags.isEmpty();
System.debug(count);
System.debug(empty);
4. remove() and clear()
texttags.remove('New');
System.debug(tags); // (VIP)
tags.clear();
System.debug(tags); // ()3. Map Collection in Salesforce Apex
In the map collection, we store not only a single value but also two values. In a map, the key is always unique, and the value can be duplicated.
The map collection is very useful for storing record IDs as keys because the keys are unique, the record IDs are also unique, and record data can be stored as values.
I use a Map when:
- I want a fast lookup by Id or some unique field.
- I have one record type that references another (like Contact → Account).
- I want to avoid nested loops and keep code bulk‑safe.
Syntax of declaring a Map collection in Apex:
Map<Datatype, Datatype> myMap = new Map<Datatype, Datatype>();
In the Apex code below, I showed you how to declare a set collection in Salesforce Apex.
Here, I declared a map collection with two different data types; you can add the same data type. Then, I added an integer as a key and a string as a value. I entered duplicate keys and values to see the result.
Then I created a map without duplicate keys, but it still contained duplicate values. Now execute this code, and you will see the result.
//Adding Duplicate keys to the Map
Map<Integer,String>AddMapValues= new Map<Integer,String>{101=>'LWC', 102=>'Apex', 103=>'LWC', 101=>'VisualForce'};
system.debug(' Values in Map collections are: ' +AddMapValues);
system.debug('---------------------------------------------------------------');
//Without duplicate key
Map<Integer,String>AddMapValue= new Map<Integer,String>{101=>'LWC', 102=>'Apex', 103=>'LWC', 104=>'VisualForce'};
system.debug(' Values in Map collections are: ' +AddMapValue);As you run the code above, you can see that the map removes duplicate keys and displays them only once. Because of removing duplicate keys, the associated value also gets removed.
Then, for the keys without repetition, all key-value pairs are displayed, even if there are duplicate values.

Common Map Methods in Apex(with examples)
1. put() – add or update entries
textMap<String, Integer> productStock = new Map<String, Integer>();
productStock.put('Laptop', 10);
productStock.put('Mouse', 25);
// Update value for existing key
productStock.put('Laptop', 12);
System.debug(productStock);
// {Laptop=12, Mouse=25}
2. get() – get value by key
textInteger laptopStock = productStock.get('Laptop');
System.debug(laptopStock); // 12
3. containsKey() – check key existence
textif (productStock.containsKey('Mouse')) {
System.debug('We have mouse stock');
}
I always do a containsKey() check before calling get() to avoid nulls.
4. keySet() and values()
textSet<String> productNames = productStock.keySet();
System.debug(productNames); // (Laptop, Mouse)
List<Integer> quantities = productStock.values();
System.debug(quantities); // e.g. (12, 25)
This is handy when you want to loop over keys or values only.
5. size(), isEmpty(), remove(), clear()
textInteger totalProducts = productStock.size();
Boolean empty = productStock.isEmpty();
productStock.remove('Mouse');
productStock.clear();Conclusion
I hope you have an idea of collections in Salesforce Apex, including their types, syntax, and examples, and how they differ from each other and their properties.
You may like to read:
- Auto-Populate Fields Using Apex Trigger in Salesforce
- Trigger Helper Class in Salesforce
- Loops in Salesforce Apex: For, While, Do-While Examples
- Salesforce Apex If Else, Nested If, and Switch Case Examples

Shubham is a Certified Salesforce Developer with technical skills for Building applications using custom objects, approval processes, validation rule salesforce flows, and UI customization. He is proficient in writing Apex classes, triggers, controllers, Apex Batches, and bulk load APIs. I am also familiar with Visualforce Pages and Lighting Web Components. Read more | LinkedIn Profile