containsAny
is a static method of the StringUtils
class that is used to check whether the given string contains any of the search characters. At least one of the search characters should be present in the string for the function to return true
.
StringUtils
is defined in the Apache Commons Lang package. Apache Commons Lang can be added to the Maven project by adding the following dependency to the pom.xml
file.
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
Note: For other versions of the commons-lang package, refer to the Maven Repository.
You can import the StringUtils
class as follows:
import org.apache.commons.lang3.StringUtils;
"abc"
"abbbcccaaaccb"
The contains.Any
function would return true
because the string contains at least one character of the search string.
"xvz"
"abcdefghti"
The contains.Any
function would return false
because the string doesn’t contain any of the search characters.
public static boolean containsAny(final CharSequence cs, final CharSequence searchChars)
final CharSequence cs
: the character sequence to check.final CharSequence searchChars
: the characters to search for.contains.Any
returns true
if any of the search characters are present in the character sequence; otherwise, it returns false
.
public static boolean containsAny(final CharSequence cs, final char... searchChars)
public static boolean containsAny(final CharSequence cs, final CharSequence... searchCharSequences)
private static boolean containsAny(final ToBooleanBiFunction<CharSequence, CharSequence> test,
final CharSequence cs, final CharSequence... searchCharSequences)
import org.apache.commons.lang3.StringUtils;public class Main{public static void main(String[] args){String characterSequence = "abbbcccaaaccb";String searchString = "abc";System.out.println(StringUtils.containsAny(characterSequence, searchString));characterSequence = "atbsljkhbv";searchString = "xyz";System.out.println(StringUtils.containsAny(characterSequence, searchString));}}
In the code below, we use an overloaded method that accepts multiple search character sequences.
import org.apache.commons.lang3.StringUtils;public class Main{public static void main(String[] args){String characterSequence = "abbbcccaaxsaccb";System.out.println(StringUtils.containsAny(characterSequence, "abc", "x", "sv"));}}