Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if an apex 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 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;
                        }
                 }
like image 703
raym0nd Avatar asked May 16 '12 21:05

raym0nd


People also ask

How do you check if a list contains an element in Apex?

mySet. addAll(myList);. You can now use the Set. contains() method to check the set for the element you're looking for.

How do you check if a list contains a value in Salesforce?

1) contains(listElement) Returns true if the list contains the specified element. 2) indexOf(listElement) Returns the index of the first occurrence of the specified element in this list. If this list does not contain the element, returns -1.

How do you check not contains in list in Salesforce?

NOT contains( 'string' ) ? The contains method returns a boolean, so you can use boolean operators on the result. You may need to check for null conditions on object / Field__c as well. You may also want to use containsIgnoreCase instead of "contains" if you want a case-insensitive check.


1 Answers

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.
like image 55
Matt K Avatar answered Oct 11 '22 09:10

Matt K