6

Possible Duplicate:
How do I iterate over each Entry in a Map?

I make the personal profiles database,and I use HashMap to collect profile.

private HashMap<String, Profile> database;

but I want to write profile data to text files

PrintWriter fileOut = new PrintWriter(new FileWriter(fileName));
fileOut.println(database.size());
for(int i = 0; i < database.size();i++){
 Profile eachProfile = database.get(key);
}

But I don't know how to get list of key to looping How can I get data from HashMap respectively with another ways?

Community
  • 1
  • 1
DrNutsu
  • 475
  • 2
  • 10
  • 21

3 Answers3

9

You could use Map.entrySet() and extended for:

for (Map.Entry<String, Profile> e: database.entrySet())
{
    String s  = e.getKey();
    Profile p = e.getValue();
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
0

Have a look at the Map documentation here: http://docs.oracle.com/javase/7/docs/api/java/util/Map.html

You want a list of all keys which is available as keySet(). The values() and entrySet() methods are related.

Robert Kühne
  • 898
  • 1
  • 12
  • 33
0

You can use map.keySet to get the set of keys. You can use map.values to get the collection of values

RNJ
  • 15,272
  • 18
  • 86
  • 131