This post will discuss how to check if a string starts with any of the given prefixes in Java.

1. Using String.startsWith() method

The String.startsWith() method returns true if the string starts with the specified prefix, false otherwise. It can be used as follows:

Download  Run Code

2. Using Stream.anyMatch() method

Starting with Java 8, you can fold the above expression into the Stream chain, and call the anyMatch() method on the stream which returns true if any elements of the stream match the provided predicate, otherwise false.

Download  Run Code

 
Before Java 8, you can easily replace the Stream API chain with a loop, as shown below:

Download  Run Code

3. Using String.matches() method

Another alternative is to use regular expressions for this task. The idea is to use the String.matches() method that checks if the string matches the given regular expression.

Download  Run Code

3. Using StringUtils.startsWithAny() method

Apache Commons Lang library has the StringUtils.startsWithAny() method which accepts varargs and checks if the string starts with any of the provided case-sensitive prefixes.

Download Code

That’s all about checking if a string starts with any of the given prefixes in Java.