Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Salesforce by (11.9k points)
edited by

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 need to use a List I can't use a Map like in this example here

What I have now is bad.

 for  (String s : allContacts)

                    {    for(String ic:insertedContacts)

                        {         if (s != ic )                          errorContacts.add(s);

                                  break;

                            }

                            break;

                        }

                 }

2 Answers

0 votes
by (32.1k points)
edited by

An apex list doesn’t support contains(). It is only available for Sets and Maps. But since you don’t want to use Maps, you can use Sets to solve this problem. For that, you can define a new set like:

Set<String> mySet = new Set<String>();

Now you’ll need to use a method such as  Set.addAll()to add all the elements of the lists to the set such as: 

mySet.addAll(myList);.

You can now use the Set.contains() method to check the set for the element you’re looking for.

0 votes
by
edited by
Now we have the contains method in the list, however, we have no contains all(list elements/set elements)to check if it contains all the elements.
in this case, you must iterate and check whether each element/record is contained or not.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...