2013-03-14 191 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中检索的值的集合。将一些(您选择的)写入文件。写入时根据需要格式化。