gpt4 book ai didi

Java - 比较列表

转载 作者:行者123 更新时间:2023-11-30 05:53:48 24 4
gpt4 key购买 nike

我有一个用 Java 编写的程序,该程序将一个简单的字符串列表文件读入 LinkedHashMap。然后它获取第二个文件,该文件由两列组成,对于每一行,查看右侧的术语是否与 HashMap 中的一个术语匹配。问题是它运行得很慢。

这是一个代码片段,这是将第二个文件与 HashMap 项进行比较的地方:

String output = "";

infile = new File("2columns.txt");
try {
in = new BufferedReader(new FileReader(infile));
} catch (FileNotFoundException e2) {
System.out.println("2columns.txt" + " not found");
}

try {
fw = new FileWriter("newfile.txt");

out = new PrintWriter(fw);

try {
String str = in.readLine();

while (str != null) {
StringTokenizer strtok = new StringTokenizer(str);

strtok.nextToken();
String strDest = strtok.nextToken();

System.out.println("Term = " + strDest);

//if (uniqList.contains(strDest)) {
if (uniqMap.get(strDest) != null) {
output += str + "\r\n";
System.out.println("Matched! Added: " + str);
}

str = in.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

out.print(output);

我从最初从 ArrayList 切换到 LinkedHashMap 后获得了性能提升,但仍然需要很长时间。我该怎么做才能加快速度?

最佳答案

您的主要瓶颈可能是您要为 while 循环的每次迭代重新创建 StringTokenizer。将其移出循环可能会有很大帮助。通过将 String 定义移到 while 循环之外可以获得轻微的加速。

最大的加速可能来自于使用 StreamTokenizer .请参阅下面的示例。

哦,正如@Doug Ayers 在上述评论中所说,使用 HashMap 而不是 LinkedHashMap :)

@MДΓΓ БДLL 关于分析您的代码的建议很有效。检查这个Eclipse Profiling Example

    Reader r = new BufferedReader(new FileReader(infile));
StreamTokenizer strtok = new StreamTokenizer(r);
String strDest ="";
while (strtok.nextToken() != StreamTokenizer.TT_EOF) {
strDest=strtok.sval; //strtok.toString() might be safer, but slower
strtok.nextToken();

System.out.println("Term = " + strtok.sval);

//if (uniqList.contains(strDest)) {
if (uniqMap.get(strtok.sval) != null) {
output += str + "\r\n";
System.out.println("Matched! Added: " + strDest +" "+ strtok.sval);
}

str = in.readLine();
}

最后一个想法是(我对此没有信心)如果最后一次性完成,写入文件也可能会更快。即,将所有匹配项存储在某种缓冲区中,并一次性写入。

关于Java - 比较列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10221358/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com