2013-03-14 187 views
4

我有一個整數,字符串(K,V)的哈希映射,並希望只寫入字符串值到一個文件(而不是鍵整數),我想只寫一些第n個條目(沒有特定的順序),而不是整個地圖。 我已經嘗試過四處尋找,但找不到寫第1個條目到文件的方法(有些例子中我可以將值轉換爲字符串數組然後執行)但是它不提供正確的格式在其中我想寫文件)從hashmap寫入一個txt文件

+1

'那麼它不提供我想要寫入文件的正確格式'你說的這種格式是什麼? – nattyddubbs 2013-03-14 15:33:38

+0

我想打印字符串,因爲它們是...每行1個...而不是列表[]的形式,即逗號分開 – mag443 2013-03-14 15:50:29

回答

0

只是流量...

獲取值的迭代器。 迭代他們增加計數器。 計數器達到n個條目時出來。

另一種方法是使用

for(int i=0, max=hashmap.size(); i<max, i<n; i++) { ... } 
+0

您可以使用計數器爲迭代器提供代碼嗎?我認爲這就是我需要的。 – mag443 2013-03-14 15:44:32

+0

夥計,你打擾了RTFM嗎?該死...... – User 2016-09-04 23:28:01

8

這聽起來像功課。

public static void main(String[] args) throws IOException { 
    // first, let's build your hashmap and populate it 
    HashMap<Integer, String> map = new HashMap<Integer, String>(); 
    map.put(1, "Value1"); 
    map.put(2, "Value2"); 
    map.put(3, "Value3"); 
    map.put(4, "Value4"); 
    map.put(5, "Value5"); 

    // then, define how many records we want to print to the file 
    int recordsToPrint = 3; 

    FileWriter fstream; 
    BufferedWriter out; 

    // create your filewriter and bufferedreader 
    fstream = new FileWriter("values.txt"); 
    out = new BufferedWriter(fstream); 

    // initialize the record count 
    int count = 0; 

    // create your iterator for your map 
    Iterator<Entry<Integer, String>> it = map.entrySet().iterator(); 

    // then use the iterator to loop through the map, stopping when we reach the 
    // last record in the map or when we have printed enough records 
    while (it.hasNext() && count < recordsToPrint) { 

     // the key/value pair is stored here in pairs 
     Map.Entry<Integer, String> pairs = it.next(); 
     System.out.println("Value is " + pairs.getValue()); 

     // since you only want the value, we only care about pairs.getValue(), which is written to out 
     out.write(pairs.getValue() + "\n"); 

     // increment the record count once we have printed to the file 
     count++; 
    } 
    // lastly, close the file and end 
    out.close(); 
} 
+4

是的,也許別人會發現它在研究一個真正的問題時很有用。編寫代碼比直接與提問者反覆試圖確定*爲什麼需要代碼更容易。我對SO純粹主義者表示歉意。 :) – AWT 2013-03-14 16:04:34

+0

它最好你解釋你的代碼,沒有解釋這段代碼是毫無價值的。正如你所說,如果他們明白的話,這對其他人會有用。沒有解釋他們可以簡單地複製/粘貼。 :) – PermGenError 2013-03-14 16:06:45

+1

感謝兄弟......這不是硬件問題....我是新來的java和有點困惑的迭代器和計數器......上面解釋了我需要 – mag443 2013-03-14 16:11:55

0

參考:Java API

試試這個

  1. 從地圖獲取值的集合。閱讀Map對象引用並找到名爲values的方法。使用此方法
  2. 迭代您在步驟1中檢索的值的集合。將一些(您選擇的)寫入文件。寫入時根據需要格式化。