Ad

Faster Way To Iterate Through If A String Contains A Phrase From Array List?

- 1 answer

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.

Ad

Answer

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));
}
Ad
source: stackoverflow.com
Ad