一旦获得匹配,您就需要停止迭代,因此假设您使用Java 8
, your for
循环可以有效地重写为下一个:
boolean match = words.stream().anyMatch(w -> p.matcher(w).matches());
您还可以使用并行化研究parallelStream()
代替stream()
特别是如果你的Set
有很多话。
如果你不使用Java 7
,仍然可以使用FluentIterable https://google.github.io/guava/releases/19.0/api/docs/com/google/common/collect/FluentIterable.html from 谷歌番石榴 https://github.com/google/guava但不幸的是没有能力并行研究。
boolean match = FluentIterable.from(words).anyMatch(
new Predicate<String>() {
@Override
public boolean apply(@Nullable final String w) {
return p.matcher(w).matches();
}
}
);
但就你而言,我不相信使用FluentIterable
比简单地添加一个更有趣break
当您获得匹配时,因为它仍然更容易阅读和维护
if (p.matcher(setWord).matches()) {
match = true;
break;
}
所以,如果你真的需要使用正则表达式你不能使用Java 8
,你最好的选择是使用break
如上所述,没有什么魔术需要考虑。
假设你会只有一个字符需要替换,可以使用startsWith(String) https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#startsWith-java.lang.String- and endsWith(String) https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#endsWith-java.lang.String-这将永远是比正则表达式快得多。像这样的东西:
// Your words should be in a TreeSet to be already sorted alphabetically
// in order to get a match as fast as possible
Set<String> words = new TreeSet<String>(); //this set is already populated
int index = word.indexOf('.');
if (index != -1) {
String prefix = word.substring(0, index);
String suffix = word.substring(index + 1);
boolean match = false;
for (String setWord : words){
// From the fastest to the slowest thing to check
// to get the best possible performances
if (setWord.length() == word.length()
&& setWord.startsWith(prefix)
&& setWord.endsWith(suffix)) {
match = true;
break;
}
}
if(match)
System.out.println("Its a match");
else
System.out.println("Its not a match");
}
else {
System.out.println("The word does not contain regex do other stuff");
}