Thursday, March 3, 2011

APEX SOQL with an IN Clause using a map.KeySet()

I've been working on some APEX that builds up a Map where the keys are Id's. It goes through several SOQL calls adding additional items that aren't already in the map. As such it is useful to exclude the items already in the map when performing the SOQL call.

Map<Id, Account> mapAccounts = new Map();

SET<ID> keys = mapAccounts.keyset();
//...

for (List<Account> listAccounts: [select Id, Name, BillingCity, BillingCountry from Account where 
 Name like :searchTerm and
 Id NOT IN :keys ]) {
 for ( Account account : listAccounts) {
  mapAccounts.put(account.Id, account);
 }
}

See Also: