Alex Rivera | Logout

How do I efficiently iterate over each entry in a Java Map?

Asked 2008-09-05T21:12:48.370
4035

If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map?

Will the ordering of elements depend on the specific map implementation that I have for the interface?

Edit
Report

2 Answers

133

Example of using iterator and generics:

Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry<String, String> entry = entries.next();
  String key = entry.getKey();
  String value = entry.getValue();
  // ...
}
answered 2009-08-18T17:34:51.543
65

The correct way to do this is to use the accepted answer as it is the most efficient. I find the following code looks a bit cleaner.

for (String key: map.keySet()) {
   System.out.println(key + "/" + map.get(key));
}
answered 2008-09-07T19:48:35.433

Your Answer