Check if an apex list contains an object

raym0nd picture raym0nd · May 16, 2012 · Viewed 38.4k times · Source

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 or C# , so I was wondering how other people are handling this.

I really need to use a List I cant use a Map like in this example here

What I have now is really bad..

                    for  (String s : allContacts)
                    {                      

                      for(String ic:insertedContacts)
                        {                          
                            if (s != ic )
                            {
                                     errorContacts.add(s);
                                     break;
                            }
                            break;
                        }
                 }

Answer

Matt K picture Matt K · May 16, 2012

A Set might be what you're looking for.

  1. Define a new Set. Set<String> mySet = new Set<String>();
  2. Use the Set.addAll() method to add all of the List elements to the set. mySet.addAll(myList);.
  3. Use the Set.contains() method to check the Set for the element you're looking for.