How do I get object from HashMap respectively?

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?


你可以使用Map.entrySet()并扩展for

for (Map.Entry<String, Profile> e: database.entrySet())
{
    String s  = e.getKey();
    Profile p = e.getValue();
}

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.


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

链接地址: http://www.djcxy.com/p/23972.html

上一篇: 如何使用循环从hashmap中获取值

下一篇: 我如何分别从HashMap获取对象?