[SalesForce] Check If String Starts With Any Of A Set

This is basically what I'm trying to accomplish:

I have a Set of strings, for example:

Set<String> emails = new Set<String>{'abuse@','database@','fbl@','ftp@'};

I also have a list of leads, if one of those leads have an email address that starts with any of those strings I need to detect it and save it into another list.

For example if a Lead's email address is: database@test.com, I need to put that lead into a List.

Best Answer

First thing that comes to my mind is to use the String substringBefore(separator) method.

String s1 = 'abuse@localhost';
String s2 = s1.substringBefore('@');
// s2 will contain 'abuse'

From there, you can use the set contains() method to see if the first part of your email matches any of your targets. You would need to adjust your emails set to leave off the @.

This would be performed on each Lead, and could be shortened to a one-liner such as

if(emails.contains(lead.email.substringBefore('@')){
    // add the lead to your special list
}