Java Checks if a String contains all words in array using Apache Commons Text

Introduction

In this article we show how to check if a String contains all words in an array in Java. By using WordUtils utility class of Apache Commons Text library you can check if the String contains all words in the given array using containsAllWords() method.

Setup Apache Commons Text in Java project

If you are using Gradle build then add the following dependency configuration into build.gradle file.

compile group: 'org.apache.commons', name: 'commons-text', version: '1.9'

Or add the following dependency XML tag to pom.xml file if you are using Maven build.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-text</artifactId>
    <version>1.9</version>
</dependency>

Or download commons-text-1.9.jar file from Apache Commons Text download page at commons.apache.org

Java code example how to use org.apache.commons.text.WordUtils.containsAllWords()

import org.apache.commons.text.WordUtils;

public class WordUtilsContainsAllWordsExample {
    public static void main(String[] args) {
        String testString = "simple solution website";

        String[] testArray = new String[] {"simple", "solution", "website"};
        boolean result1 = WordUtils.containsAllWords(testString, testArray);
        boolean result2 = WordUtils.containsAllWords(testString, "simple", "solution");
        boolean result3 = WordUtils.containsAllWords(testString, "simple");

        boolean result4 = WordUtils.containsAllWords(testString, "simple", "video");
        boolean result5 = WordUtils.containsAllWords(testString, "web");
        boolean result6 = WordUtils.containsAllWords(testString, "web", "site");

        System.out.println(result1);
        System.out.println(result2);
        System.out.println(result3);
        System.out.println(result4);
        System.out.println(result5);
        System.out.println(result6);

    }
}
Output:

true
true
true
false
false
false

Happy Coding 😊