[英]Printing a HashMap into a .txt file
現在,我正在嘗試使用我的這種方法來打印HashMap的.txt文件,該文件包含一個單詞作為Key,以及它在讀取的.txt文件中出現的次數(通過另一種方法完成)一個值。 該方法需要按字母順序放置HashMap鍵,然后在單獨的.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依次遍歷地圖的鍵
這是增強的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 ) );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.