现在,我试图让我的这个方法打印一个 HashMap 的 .txt 文件,其中包含一个单词作为键,以及它在读取的 .txt 文件中出现的次数(在另一个文件中完成)方法)作为值。该方法需要将 HashMap Key 按字母顺序排列,然后在单独的 .txt 文件中打印旁边相应的 Value。
这是我的方法代码:
public static void writeVocabulary(HashMap<String, Integer> vocab, String fileName) {
// Converts the given HashMap keys (the words) into a List.
// Collections.sort() will sort the List of HashMap keys into alphabetical order.
List<String> listVal = new ArrayList<String>(vocab.keySet());
Collections.sort(listVal);
try
{
// Creating the writer
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName)));
for (int i = 1; i < listVal.size(); i++) {
out.println(listVal.get(i) + " " + vocab.get(i));
}
out.close();
}
// Catching the file not found error
// and any other errors
catch (FileNotFoundException e) {
System.err.println(fileName + "cannot be found.");
}
catch (Exception e) {
System.err.println(e);
}
}
我的问题是,虽然打印了 .txt 文件,并且单词采用完美的 ASCII 顺序(我需要的),但该单词旁边的每个值都返回 null。我尝试了很多不同的方法来解决这个问题,但没有效果。我认为问题出在我的“for”循环中:
for (int i = 1; i < listVal.size(); i++) {
out.println(listVal.get(i) + " " + vocab.get(i));
}
我很确定我的逻辑是错误的,但我想不出解决方案。任何帮助将非常感激。提前致谢!
最佳答案
您需要使用正确的映射键从映射中获取值 - 此代码当前使用列表中的索引,而不是列表中的值(这是映射的实际键)。
for (int i = 0; i < listVal.size(); i++) {
out.println(listVal.get(i) + " " + vocab.get(listVal.get(i)));
}
如果您想要所有项目,也从索引 0 开始(请参阅上面循环中的初始条件)。正如评论中所建议的,您也可以使用 TreeMap 按顺序迭代 map 的键
关于java - 将 HashMap 打印到 .txt 文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571200/