When you work with real-world Apex code, you almost always end up converting between List, Set, and Map to make your logic cleaner and faster.
While working with List collections in Apex, you often encounter situations such as removing duplicate values or accessing records by their IDs. Instead of writing extra logic to handle these cases, you can use Set and Map collections, which make the task easier.
A Set helps you automatically remove duplicates, and a Map lets you quickly find records by their ID or other keys. That’s why we sometimes need to convert a List into a Set or a Map to use it more efficiently.
In this tutorial, we will learn about collections in Salesforce Apex and how to convert Apex List collections to Set and Map collections.
Why Convert a List to a Set or a Map in Apex?
Let me quickly set the context.
In Apex:
- A List is ordered and allows duplicates.
- A Set is unordered and only keeps unique values.
- A Map stores key–value pairs, like
Id => Account.
So in real code, you often:
- Start with a List (usually from SOQL).
- Convert it to a Set when you want unique values (like a list of IDs with no duplicates).
- Convert it to a Map when you want fast lookup by key (like Id -> record).
Common scenarios:
- Bulk triggers where you pull IDs from a List of records and need them to be unique.
- Service layer where you need a Map<Id, sObject> for quick record access.
- Validation logic that checks whether a value exists without looping through the full list repeatedly.
Collection Variable in Salesforce Apex
In Salesforce Apex, collection data types are used to store similar information together. The collection data type can store multiple values. For example, if you want to store multiple integers together, you can use a collection.
There are three types of collections in Salesforce Apex:
1. List Collection in Apex
The List collection data type stores information sequentially with an index. The list index always starts from 0. In Apex, the list size can be increased or decreased at runtime, depending on the number of elements added to it.
- When we execute the list, we get the output in sequential order.
- The values can be duplicated in the list; the list doesn’t prevent duplicates in the apex collection.
Syntax of declaring a List collection:
List <Datatype> myList = new <Datatype>();List<Integer>myList = new List<Integer>{1,8,6,4,6,9}; //OR
List<Integer>myList = new List <Integer>();
myList.add (5);
myList.add (15);
myList.add (9);
system.debug( 'Collection of List is: ' +myList); // 5, 15, 92. Set Collection in Apex
Set collections are similar to lists but have some properties that differ from those of lists. The elements in the set collection are stored in an unordered format. The Set collection does not return duplicate values.
Syntax of declaring a Set collection:
Set<Datatype> mySet = new <Datatype>();Set<Integer>mySet= new Set<Integer>{4,6,3,8,7,2}; //OR
Set<Integer>mySet = new Set<Integer>();
mySet.add (4);
mySet.add (2);
mySet.add (8);
system.debug( 'Collection of Set is: ' +mySet); // 2, 4, 83. Map Collection in Apex
In the Map collection in Apex, we can store two values in a key-value pair, each associated with a particular key. The key is always unique in the map, and the value can be duplicated.
Let’s take a student’s roll number and name as an example. Here, the roll number acts as a key, and the name as a value, meaning that two students’ names can be the same in the class, but their roll numbers are unique.
Syntax of declaring a Map collection:
Map<Key_Datatype,Value_Datatype> mapList = new Map<Key_Datatype,Value_Datatype>();Map<Integer,String> mapList = new Map<Integer,String>();
mapList.put(1,'Alex');
mapList.put(2,'Emma');
mapList.put(3,'Jhon');
mapList.put(4,'Alex');
system.debug( 'Collection of Map is: ' +mapList); // {1=Alex, 2=Emma, 3=Jhon, 4=Alex}Convert Apex List to Set and Map Collections in Salesforce
Below, I will provide examples and explain how we can convert a list into a set and a map collection in Salesforce Apex.
Convert the Apex List into a Set Collection
Now, let’s look at a real-time example where we need to convert an Apex List to a Set. I will explain how to achieve this in Salesforce Apex code.
Example 1: Remove Duplicate Values from a List
Suppose you have a list of contacts, and some contact records have the same/duplicate email address. Now, we want to work only on records with unique email addresses.
public with sharing class ListToSetColleciton {
public void ListToSet() {
List<Contact> contacts = [SELECT Email FROM Contact WHERE Email != NULL];
List<String> emailList = new List<String>();
for(Contact c : contacts){
emailList.add(c.Email);
}
Set<String> uniqueEmails = new Set<String>(emailList);
System.debug(uniqueEmails);
}
}In the above Apex class, we have contact records in a list collection that also contains duplicate emails. Now, we only want the unique emails, and we know we can store them in a set.
So, here we need to convert the List to a Set, and then we can get the unique email addresses in the Set.

Example 2: Enable Quick Access to Record Values
For example, you want to check whether a product code exists in Salesforce.
Now, instead of searching the list directly, we convert it into a Set of product codes to remove duplicates and enable faster lookup.
public with sharing class ListToSetColleciton {
public static void checkProductCode(String inputProductCode) {
List<Product2> products = [SELECT ProductCode FROM Product2 WHERE ProductCode != NULL];
Set<String> productCodes = new Set<String>();
for(Product2 p : products) {
productCodes.add(p.ProductCode);
}
if(productCodes.contains(inputProductCode)) {
System.debug(' -----Product code exists: ' + inputProductCode);
} else {
System.debug(' -----Product code does NOT exist: ' + inputProductCode);
}
}
}In the above Apex class, we retrieved all products where ProductCode is not null, and the results are stored in a List<Product2>.
Using a loop, we added each ProductCode from the list to a Set<String> to ensure duplicates are automatically removed. Then, for faster lookups, use the contains() method.

The image below shows the Product Code we checked in the above testing output, confirming that the product code exists.

In this way, we can convert the List into a Set collection in Salesforce Apex to avoid duplicates and improve data handling.
Convert Apex List into a Map Collection
Now, let’s look at a real-time example where we need to convert an Apex List to a Map. I will explain how to achieve this in Salesforce Apex code.
Example 1: Access Records by IDs
Suppose you have a list of accounts. You need to access the account records using their IDs.
public with sharing class ListToSetColleciton {
public static void convertListToMapExample() {
List<Account> accountList = [
SELECT Id, Name, Industry
FROM Account
WHERE Industry != null
];
Map<Id, Account> accountMap = new Map<Id, Account>(accountList);
for (Id accId : accountMap.keySet()) {
Account acc = accountMap.get(accId);
System.debug(' Account Name: ' + acc.Name + ' && Industry: ' + acc.Industry);
}
}
}In the above Apex class, we converted the List to a Map and then to accountMap.keySet() gives us a set of Account IDs, which are the keys in the map.
The for each loop iterates through each account ID present in the map’s key set. For each ID, it retrieves the corresponding account object from the Map using accountMap.get(accId) method.
Once the Account record is retrieved, it prints the account’s name and industry using the System.debug() method, allowing us to view the details of each Account in the debug logs.

Example 2: Access Contacts and Opportunities by Account IDs
For example, you query two different lists (Contacts and Opportunities) and want to match them based on AccountId in Salesforce. Converting the List to a Map will be helpful for this use case.
public with sharing class ListToMapCollection {
public static void matchByAccountId() {
List<Contact> contacts = [SELECT Id, Name, AccountId FROM Contact WHERE AccountId != NULL];
List<Opportunity> opps = [SELECT Id, Name, AccountId FROM Opportunity WHERE AccountId != NULL];
Map<Id, List<Contact>> accountToContactsMap = new Map<Id, List<Contact>>();
for(Contact c : contacts){
if(!accountToContactsMap.containsKey(c.AccountId)){
accountToContactsMap.put(c.AccountId, new List<Contact>());
}
accountToContactsMap.get(c.AccountId).add(c);
}
for(Opportunity opp : opps){
List<Contact> relatedContacts = accountToContactsMap.get(opp.AccountId);
if(relatedContacts != null){
System.debug('Opportunity: ' + opp.Name);
for(Contact con : relatedContacts){
System.debug(' - Related Contact: ' + con.Name);
}
}
}
}
}In the above Apex class, we retrieved all contacts and opportunities associated with an account, i.e., an AccountId that is not null.
Then, we grouped the contacts by AccountId using a Map, so that all contacts associated with the same account were stored together.
Then, the for loop iterates over each opportunity and checks whether any contacts have the same AccountId.
If a match is found, it prints the opportunity name along with the names of the related contacts.

In this way, we can convert the List into a Map in Salesforce Apex to easily access the record IDs along with their accounts.
Conclusion
I hope you have an idea of the collections in Salesforce Apex and how to convert Apex List to Set and Map collections. We have seen the different collection variables, their syntax, and how they can help convert List, Set, and Map collections in Apex.
You may like to read:
- Variables and Data Types in Salesforce Apex
- Convert Integer Data Type to Decimal in Salesforce Apex
- Convert Integer Data Type to String in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.