将HashMap打印到.txt文件中

时间:2015-04-10 21:48:25

标签: java filewriter

现在,我试图让我的这个方法打印一个包含单词作为键的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。我尝试了许多不同的方法来解决这个问题,但无济于事。我认为问题出在我的'&#39; for&#39;循环:

   for (int i = 1; i < listVal.size(); i++) {
    out.println(listVal.get(i) + " " + vocab.get(i));
      }

我很确定我的逻辑是错误的,但我无法想到解决方案。任何帮助将非常感激。提前谢谢!

3 个答案:

答案 0 :(得分:3)

您需要使用正确的映射键从映射中获取值 - 此代码当前使用List中的索引,而不是列表中的值(这是映射的实际键)。

for (int i = 0; i < listVal.size(); i++) {
    out.println(listVal.get(i) + " " + vocab.get(listVal.get(i)));
}

如果你想要所有项目,也可以从索引0开始(参见上面循环中的初始条件)。正如评论中所建议的那样,您也可以使用TreeMap按顺序迭代地图的键

答案 1 :(得分:1)

这是增强的for循环可以防止你犯错的地方。您可以使用Map

get(key)获取值
for ( String key : listVal ) {
    out.println( key + " " + vocab.get(key) );
}

答案 2 :(得分:1)

您不需要使用索引遍历列表;相反,你可以使用:

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 ) );
}
相关问题