This post will discuss how to check if a string contains any of the substrings from a List.

1. Using String.contains() method

The idea is to iterate over the entire list using an enhanced for loop and call the String.contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.

Download  Run Code

 
If you need the actual substring that is contained in the string, you can tweak the above utility function like:

Download  Run Code

2. Using Java 8

Starting with Java 8, you can use Stream API for this task. The idea is to call the anyMatch() method on the stream elements, which return true if and only if any element matches with the supplied predicate. To check for a substring, you can use the contains() method.

Download  Run Code

 
Alternately, you can filter elements with the filter() method to get the actual substring contained in the string, as shown below:

Download  Run Code

3. Using Apache Commons Lang

Finally, you can leverage the Apache Commons Lang library, which provides the indexOfAny() method in the StringUtils class. It will return the first index of any of a set of given substrings, -1 for no match or null input. However, it accepts varargs, so you have to convert the list to a String array first, as shown below:

Download Code

That’s all about checking if a string contains any of the substrings from a List.