Home > other >  Faster way to iterate through if a string contains a phrase from array list?
Faster way to iterate through if a string contains a phrase from array list?

Time:03-17

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.

CodePudding user response:

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));
}
  • Related