What is the best way to check if a string contains an element from a list?

for example:

String email= 'itairu@gmail.com'
List<String> domainNames = split by ; from domains in a custom setting 

for example : (domainNames = [0] - gmail.com, [1] - example.com, [2] - mof.com);

How can I check if email field is contains one of the values in the domainName's List?

I can do it with a Boolean field that will be turned to true if one of field is found for this case -

boolean found = false;
for(String s : domainNames ){
   found =true;  


I want to know if there is a better way - in case I will have a huge amount of values to move on in the for loop for this.


2 Answers 2


A shorter version of your code just checks the domain directly:

Boolean found = domainNames.contains(email.split('@',2)[1]);

There's other ways to do this, too, but this is probably the most straightforward version.


If you have control over the type of domainNames, you should consider changing its type to Set<string>. Sets hash their values, so checking whether they contain a particular value takes the same amount of time regardless of the number of elements in the set, compared to a List which must go through each element until it finds one that matches.

Set<String> domainNames = new Set<String>{'example.com', 'gmail.com'};
domainNames.contains(email.split('@', 2)[1]);

Also, the general solution to the question of whether a particular string contains any strings in a list where they could be in any part of the input string would be to do what you did, except you would use a break statement to end the loop once you've found a match:

boolean found = false;
for(String s : domainNames ){
         found = true;  
  • Thanks a lot. Both of the answers helped me but unfortunately, I can give the best answer only to one.
    – Salvation
    Dec 10, 2018 at 6:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.