Convert Apex List to Set and Map Collections in Salesforce
This guide breaks down how to convert Apex List collections into Set and Map collections in Salesforce to improve code efficiency and data handling. It shows how Sets can be used to remove duplicates and speed up value checks, and how Maps allow for fast record access by key, such as record IDs. Practical examples include removing duplicate emails from contact lists, checking product codes quickly, and accessing accounts or matching contacts with opportunities by their Account IDs. By converting Lists appropriately, Salesforce developers can write cleaner, faster Apex code for common scenarios like triggers and service layers.
- Convert Lists to Sets in Apex to automatically remove duplicate values.
- Use Maps to quickly access records by their unique keys like record IDs.
- Group related records by keys using Map of Id to List for complex data relationships.
- Leverage Set.contains() for faster membership checks than looping through Lists.
- Declare and initialize collections using standard Apex syntax for Lists, Sets, and Maps.
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 .