I want to see if any of the strings I pass(num) starts with any of the values on my set

  Ex. String num = 456987533;

  Set<String> numValidator = new Set<String>{‘456’,’312’,762’};

Since my num starts with ‘456’ it should come back true.

How can I write this out?

StartsWith does not work because it is only comparing a string and not a set

1 Answer 1


Unless all of your String prefixes are the same length, you'll need to iterate over the contents of your Set.

  for (String s : numValidator) {
       if (myInputString.startsWith(s)) {
           // do something

However, if all of your prefixes are exactly three characters, you can handle this more simply and make use of Set membership constant-time checking:

Set<String> numValidator = new Set<String>{'456','312','762'};
String myInputString = '312456';

if (numValidator.contains(myInputString.left(3))) {
    System.debug('Found it');
  • One more creative option would be to turn numValidator into a regex pattern and look for matches against the input string.
    – Mark Pond
    Aug 29, 2018 at 17:10

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.