Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading