Back

Explore Courses Blog Tutorials Interview Questions
0 votes
1 view
in Salesforce by (11.9k points)

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;

                        }

                 }

2 Answers

0 votes
by (32.1k points)

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
Now we have contains method in 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 each element/record is contained or not.
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...