Skip to main content

List

Get Ids from List of SObjects

Use Map constructor Map<ID,sObject>(recordList) to get Ids from List of SObjects.

// Keeping accounts as variable, because source of records can be different e.g. method's input
List<Account> accounts = [SELECT Id FROM Account];

Set<Id> accountIds = new Set<Id>();

for (Account acc : accounts) {
accountIds.add(acc.Id);
}

// Keeping accounts as variable, because source of records can be different e.g. method's input
List<Account> accounts = [SELECT Id FROM Account];

Set<Id> accountIds = new Map<Id, Account>(accounts).keySet();
List<Id> accountIds = new List<Id>(new Map<Id, Account>(accounts).keySet());