我正在比较两个字符串列表以找到可能的匹配项。示例:
public class Tester {
public static void main(String[] args) {
List<String> test = new ArrayList<String>();
List<String> test2 = new ArrayList<String>();
test.add("3H0875AAAA0012");
test.add("3H0875AABB0018");
test.add("3H0875AAAC0010");
test2.add("3H0875AA");
for(String s2: test2){
for (String s: test){
if (s.matches(".*" + s2 + ".*")){
System.out.println("Match");
}
}
}
}
}
基本上对于 test2
中的每个字符串,我想看看 test
中是否有任何字符串完全或部分包含 test2
。上面代码的输出应该是:
Match
Match
Match
但是,在我的真实案例场景中,我在测试中有大约 225K 个字符串,在 test2 中有大约 5K 个字符串。这个比较过程花费的时间太长,想看看是否可以优化比较。分析 test2 中的前 1.5K 项大约需要 10 分钟。因此完成比较至少需要 30 到 40 分钟。
提前致谢
最佳答案
我认为你不应该为此使用 regex:我相信查看 String#contains
(这里是 link to its javadoc entry)会给你更好的结果, 在性能方面 ;)
例如,您的代码可以是:
for(final String s2: test2){
for (final String s: test){
if(s.contains(s2)) {
System.out.println("Match");
}
}
}
关于java - 大型列表的正则表达式优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22951558/