'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.
Solution 1:[1]
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));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
