1

At the moment I have this:

try{
            // Create file 
            FileWriter fstream = new FileWriter("output");
            BufferedWriter out = new BufferedWriter(fstream);
            Iterator mapIt = assignments.entrySet().iterator();
            while (mapIt.hasNext()){
                out.write(mapIt.next().toString()+";\n");
            }
            //Close the output stream
            out.close();
        }

The thing is, I can't just take the toString() of iterator, I need to take out the key and the value separately so I can put some stuff between them in the outputfile. Does anyone know how I do this?

Chucky
  • 1,701
  • 7
  • 28
  • 62
  • possible duplicate of [How do I iterate over each Entry in a Collection Map?](http://stackoverflow.com/questions/46898/how-do-i-iterate-over-each-entry-in-a-collection-map) – Graham Borland Feb 17 '12 at 16:50

3 Answers3

3

You will notice the iterator returns a Map.Entry which has getKey and getValue methods.

Use those to get the respective items....something like

while (mapIt.hasNext()){
   Map.Entry entry = mapIt.next();
   Object key = entry.getKey();
   Object value = entry.getValue();
   // format away..
}

Note I put Object as the types of key and val, but you should specify the types according to however you defined the Map.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
1

Since the iterator returns a set of Map.Entry, you can get the key and value separately out of that:

http://docs.oracle.com/javase/6/docs/api/java/util/Map.Entry.html

duffymo
  • 305,152
  • 44
  • 369
  • 561
1

From How to efficiently iterate over each Entry in a Map?

for (Map.Entry<String, String> entry : map.entrySet())
{
    System.out.println(entry.getKey() + "/" + entry.getValue());
}
Community
  • 1
  • 1
Graham Borland
  • 60,055
  • 21
  • 138
  • 179