Press ESC to close

Extracting Record IDs from SObject Lists in Apex: The Cleanest Way to Do It

If you’ve been working with Salesforce Apex for any amount of time, you’ve probably come across a common need: extracting a list of record IDs from a list of SObject records. Whether you’re building queries, filtering logic, or batch processing, this little operation happens everywhere.

In this post, we’ll walk through common approaches to extracting IDs — from the traditional loop to more elegant and efficient methods — and explain when to use each.

Simple Loop

This is the most straightforward and familiar approach. You loop through the list of records, access the .Id field, and build a new List<Id>.

List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name LIKE 'Test%']; List<Id> accountIds = new List<Id>();  for (Account acc : accountList) {     accountIds.add(acc.Id); }

Cleaner and More Flexible

Apex provides a built-in way to turn a list of records into a Map<Id, SObject> using the list constructor. From there, retrieving the IDs is as simple as calling .keySet().

List<Account> accountList = [SELECT Id, Name FROM Account WHERE Name LIKE 'Test%'];  Map<Id, Account> accountMap = new Map<Id, Account>(accountList); Set<Id> accountIds = accountMap.keySet();

If you specifically need a List<Id>, you can convert the set easily:

List<Id> accountIdList = new List<Id>(accountIds);

Pros:

  • Very concise
  • You get both the ID list and the Map<Id, Record> for later use
  • Avoids manual looping

Cons:

  • Slightly more memory usage if you only need the IDs

This approach is useful when you’re doing follow-up lookups or record grouping by ID. It’s often my go-to solution in real-world projects.

If you’re just looking to grab the IDs, a loop works fine. But if you’re building something more robust — maybe you’ll need the records again later — using a Map<Id, SObject> is a cleaner and more scalable solution.

It’s one of those little techniques that make Apex code more maintainable and expressive. Small things add up.

Leave a Reply

Your email address will not be published. Required fields are marked *