What is StringUtils.containsAny() in Java?

containsAny is a static method of the StringUtils class that checks whether a given string contains any of the characters/strings in the given set of characters/strings. At least one search character/string should be present in the string for this function to return true.


The comparison is case-sensitive in nature.

How to import StringUtils

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;

Syntax


public static boolean containsAny(CharSequence cs, CharSequence searchChars)

Parameters

The function takes in two parameters:

  • CharSequence cs: Character sequence to check.
  • searchChars: The characters to search for.

Return value

The function returns true if the character sequence contains any search characters. Otherwise, it returns false.


The function will return false in case of a null parameter.

Overloaded methods

public static boolean containsAny(CharSequence cs, char... searchChars)
public static boolean containsAny(CharSequence cs, CharSequence... searchCharSequences)

Code

In the code below, we define a sequence of characters and search characters.

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));
searchString = "xyz";
System.out.println(StringUtils.containsAny(characterSequence, searchString));
}
}

Explanation

  1. search string = "abc".
    string = "abbbcccaaaccb"

Since the string contains at least one character from the search string (abc), the function returns true.

  1. search string = "xyz"
    string = "abbbcccaaaccb"

Since the string does not contain at least one character from the search string (xyz), the function returns false.

Output

The output of the code will be as follows:


true
false

Free Resources