Trusted answers to developer questions

What is WordUtils.containsAllWords in Java?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

containsAllWords is a static method of the WordUtils class that is used to check whether the given string contains all the words in a given array of words.


The comparison is case-sensitive.

Add apache commons-lang package

WordUtils is defined in the Apache Commons Text package. Apache Commons Text 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-text</artifactId>
            <version>1.9</version>
</dependency>

For other versions of the commons-text package, refer to the Maven Repository.

Import WordUtils

You can import the WordUtils class as follows:


import org.apache.commons.text.WordUtils;

Syntax


public static boolean containsAllWords(final CharSequence word, final CharSequence... words)

Parameters

  • final CharSequence word: the string/character sequence to check.

  • final CharSequence... words: list of words to search.

Returns

true if all the search words are found in the string else false

Code

Example 1

  • text = "hello educative, how are you?!";
  • list of words = ["hello", "educative"]

Applying the containsAllWords function would result in true as all the words are present in the text.

Example 2

  • text = "hello educative, how are you?!";

  • list of words = ["hello", "educative", "HOW"]

Applying the containsAllWords function would result in false as the word HOW is not present in the text, and the comparison is case-sensitive

Example 3

  • text = "hello educative, how are you?!";

  • list of words = ["hello", "educative", "him"]

Applying the containsAllWords function would result in false as the word him is not present in the text.

import org.apache.commons.text.WordUtils;
public class Main {
public static void main(String[] args) {
String text = "hello educative, how are you?!";
boolean flag = WordUtils.containsAllWords(text, "hello", "educative");
System.out.println(flag);
flag = WordUtils.containsAllWords(text, "hello", "educative", "HOW");
System.out.println(flag);
flag = WordUtils.containsAllWords(text, "hello", "educative", "him");
System.out.println(flag);
}
}

Output


true
false
false

RELATED TAGS

java
wordutils
Did you find this helpful?