现在,我正在尝试让我的这种方法打印一个包含单词作为键的 HashMap 的.txt文件,以及它在读取.txt文件中出现的次数(在另一种方法中完成)作为值。该方法需要按字母顺序放置 HashMap 键,然后在单独的.txt文件中打印旁边的相应值。
这是我的方法代码:
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));
}
我很确定我在这方面的逻辑是错误的,但我想不出解决方案。任何帮助将不胜感激。提前感谢!
您需要使用正确的映射键才能从映射中获取值 - 此代码当前使用 List 中的索引,而不是列表中的值(这是映射的实际键)。
for (int i = 0; i < listVal.size(); i++) {
out.println(listVal.get(i) + " " + vocab.get(listVal.get(i)));
}
如果您想要所有项目,也从索引 0 开始(请参阅上面的循环中的初始条件)。如注释中所建议的,您也可以使用树状图按顺序迭代映射的键
这就是增强的 for 循环可以防止您犯错误的地方。您可以使用get(key)
从Map
获取值:
for ( String key : listVal ) {
out.println( key + " " + vocab.get(key) );
}
您不需要使用索引循环访问列表; 相反,您可以使用:
for ( final String key : listVal ) {
out.println( key + " " + vocab.get( key ) );
}
您可以使用 TreeSet 进行排序,进一步简化事情:
for ( final String key : new TreeSet<String>( vocab.keySet() ) ) {
out.println( key + " " + vocab.get( key ) );
}