This post will check if a string ends with any of the given suffixes in Java.

There are several ways to check if a string ends with any of the given suffixes in Java. Here are some of them:

1. Using OR operator

We can use the String.endsWith() method, which returns true if the string ends with the specified suffix, and false otherwise. We can use this method with an OR operator to check the string against all possible suffixes.

Download  Run Code

2. Using Streams API

We can also use Streams API starting from Java 8. The anyMatch() method returns true if any element of the stream matches the predicate, and false otherwise. For example, we can use the following code to check if a string matches one of the given suffixes:

Download  Run Code

 
This is equivalent to:

Download  Run Code

3. Using Apache Commons Lang

We can use external libraries such as Apache Commons Lang, which provides the StringUtils.endsWithAny() method. This method takes a string and an array of suffixes as arguments and returns true if the string ends with any of the suffixes, and false otherwise.

Download Code

4. Regular expressions

Finally, you can check if a string matches one of the given suffixes using the String.matches() method. It returns true if the string matches a given regular expression, and false otherwise. To specify multiple suffixes in the regex, we can use the | symbol. To indicate the end of the string in the regex, we can use the $ symbol. For example,

Download  Run Code

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