---
title: "Get set of Ids from SObject List"
url: "https://blog.beyondthecloud.dev/tips/get-set-of-ids-from-sobject-list"
category: "Apex"
tags: "soql"
published: "2024-01-02"
---

# Get set of Ids from SObject List

Get set of Ids from your SObject list without iteration

### Get set of Ids from your SObject list without iteration

You don’t need to iterate through the list of SObjects to get the set of their Ids:

```apex
Set<Id> leadsIds = new Set<Id>();

for (Lead l : leads) {
    leadsIds.add(l.Id);
}
```

You can simply cast your List to Map and then use keyset:

```apex
Set<Id> leadsIds = (new Map<Id, Lead>(leads)).keySet();
```

Get set of Ids from your SObject list without iteration

You can also do that directly on SOQL query result:

```apex
Set<Id> leadsIds = new Map<Id, Lead>([
    SELECT Id FROM Lead LIMIT 10
]).keySet();
```
