Check if an apex list contains an object
Asked Answered
T

1

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;
                        }
                 }
Tracy answered 16/5, 2012 at 21:2 Comment(0)
R
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.
Regazzi answered 16/5, 2012 at 21:15 Comment(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.Impersonal
salesforce drives me mad too.Jaqitsch
<apex:repeat> can be used to iterate over a map, too. salesforce.stackexchange.com/a/9323/72Regazzi
@MattK yes, but only in visualforce, the question is related to Apex code.Twentytwo

© 2022 - 2024 — McMap. All rights reserved.