Back
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; } }
for (String s : allContacts)
{ for(String ic:insertedContacts)
{ if (s != ic ) { errorContacts.add(s);
break;
}
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.
1.2k questions
2.7k answers
501 comments
693 users