6

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

for example:

String email= '[email protected]'
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 ){
 if(email.contains(s)){
   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.

Thanks!

3 Answers 3

10

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.

0
4

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 ){
     if(email.contains(s)){
         found = true;  
         break;
     }
}
1
  • 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
0

in general:

any list that you want to check that at least one of the items contains in a string you can create a util function.

Assert.isTrue(ApxUtil.itemListInString('My test', new List<String>{'test'}));
Assert.isTrue(ApxUtil.itemListInString('My test', new List<String>{'other'}));

public static Boolean itemListInString(String val, List<String> items){
        if(String.isBlank(val))return false;
        for(String item : values){
            if(val.contains(item)) return true;
        }
        return false;
    }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .