Home > Java Core > How to check if any word from a List exists in a String in Java8

How to check if any word from a List exists in a String in Java8

In this article, we will learn how to check if any word from a list of keywords exists in a String using Java 8 stream API.

We have an input string and a list of words, we will check if any of the words from the list exists in the input string or not.

String inout = "We love to code in Java8 and Python";

And we also have a list of keywords listed below –

List <String> list = new ArrayList();
        list.add("xml");
        list.add("XSLT");
        list.add("html");
        list.add("python");
        list.add("java");
        list.add("java8");
        list.add("ruby");
        list.add("rails");

In the below code we have first converted out input string and list of keywords in lower case to handle case insensitivity. After that we used the Java8 stream API to get the first matched word, using the methods –

stream()
filter()
findAny() and 
orElse() 

Code:

    public static boolean checkIfAnyListWordMatches(String inputText, List<String> keywords){
        String matchingWord = keywords.stream()
                .filter(s -> inputText.matches(".*\\b"+s.toLowerCase()+"\\b.*"))
                .findAny()
                .orElse(null);

        log.info(matchingWord);

        return matchingWord == null ? Boolean.FALSE : Boolean.TRUE;
    }

    public static void main(String[] args) {
        String string="We love to code in Java8 and Python";

        List <String> list = new ArrayList();
        list.add("XML");
        list.add("xslt");
        list.add("html");
        list.add("java");
        list.add("java8");
        list.add("Python");
        list.add("Ruby");
        list.add("Go");

        boolean isMatched = checkIfAnyListWordMatches(string.toLowerCase(), list);

        log.info("Any word exists? -> " + isMatched);
    }

We have used filter() and collect() of the Java Stream API in the above case. The result will the list of keywords found in the input string (if any) or an empty list. Before doing the matching we converted the input string and the values in the list in lower case to handle case insensitive.

Output:

Any word exist? -> true