11

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;
                        }
                 }
raym0nd
  • 3,172
  • 7
  • 36
  • 73

1 Answers1

26

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.
Matt K
  • 7,207
  • 5
  • 39
  • 60
  • 4
    Sometimes I am driven mad by salesforce. I need to store a list of unique key value pairs. First I wanted to use lists but I did not want to iterate through all elements to prevent inserting a duplicate key value. I thought of using maps since they have a containskey() method to check for duplicates before insertion. I also need to expose this data to visualforce and looks like maps cannot be bound to visualforce elements like apex:repeat. – Richard N Aug 27 '12 at 22:57
  • 2
    salesforce drives me mad too. – edgartheunready Feb 21 '14 at 16:23
  • 1
    `` can be used to iterate over a map, too. http://salesforce.stackexchange.com/a/9323/72 – Matt K Jan 21 '16 at 19:21
  • @MattK yes, but only in visualforce, the question is related to Apex code. – Alberto Mar 16 '17 at 14:37