[SOLVED] Faster way to iterate through if a string contains a phrase from array list?

Table of Contents

Issue

I’m iterating my string through an array of phrases with this code:

public boolean checkName(String nameInputed, ArrayList<String> phraseList) {
    
    boolean match = false;        
    for (String phrase : phraseList) {
        if (nameInputed.matches(".*" + phrase + ".*")) {
            result = true;
        }
    }
    return match ;
}

I’m wondering if there is a faster way to check with a large list of phrases.

Solution

What about…

public boolean checkName(String nameInputed, java.util.List<String> phraseList) {
    return phraseList.stream()
                     .filter(phrase -> nameInputed.contains(phrase))
                     .findFirst()
                     .isPresent();
}

And if you don’t want to use stream API then how about…

public boolean checkName(String nameInputed, java.util.List<String> phraseList) {
    for (String phrase : phraseList) {
        if (nameInputed.contains(phrase)) {
            return true;
        }
    }
    return false;
}

Edit

As @user16320675 suggested in this comment

public boolean checkName(String nameInputed, java.util.List<String> phraseList) {
    return phraseList.stream()
                     .anyMatch(phrase -> nameInputed.contains(phrase));
}

Answered By – Abra

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *