+ Start a Discussion
waylonatcimwaylonatcim 

Check if a list contains an object

Is there any way to check if a list contains a certain element?  I looked at the List functions and did not see any contain() function like Java has, so I was wondering how other people are handling this.
 
Thanks
wintamutewintamute
Hi,

List doesn't support contains(), this method is only available for Sets and Maps (here its containsKey() actually).
Please note that you can only use primitive types in sets and as key in maps.
So one solution for objects would be to use a map with the object id as key, for example
Code:
Map<Id,Account> accountMap = new Map<Id,Account>():

accountMap.put(sampleAccount.Id, sampleAccount);

if(accountMap.containsKey(sampleAccount.Id)) {
   // do foo
}

Hope this helps,
Andreas




Message Edited by wintamute on 11-18-2008 08:41 PM
waylonatcimwaylonatcim
Thanks for the reply, this is exactly what I needed.
Subhasis SanyalSubhasis Sanyal
   // Inline Convert the String Array / List to Set since List does not support contains()
   private static final Set<String> validCountries = new Set<String>(new String[] {'Germany', 'India', 'Japan', 'United States'});
    if (validCountries.contains(countryName)) {
        // Do your Logic
    } 
 
Fabien TaillonFabien Taillon