Thursday, 9 February 2023

How can I efficiently get a Set from a List ?

 Lets assume we have List<Account> record, we need to get all account record id in a set.

List<Account> accList = [select id,name from Account limit 10];

system.debug('acclist--'+accList);

We have accList , need to get account Record id,

Earlier approach is iterating over loop 

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

for(Account acc:accList ){

    accidSet.add(acc.id);

}

System.debug('accidSet--'+accidSet);

However the efficient way will be 

Set<Id> accidSet = (new Map<Id,Account>(accList)).keySet();

system.debug('accIdSet--'+accidSet);

No comments: