Rate this page

Iterate over a map in Java

Tested on

Java SE (7*, 8)
* no lamba expressions


To perform a given action for each entry of a java.util.Map.


Suppose you have a java.util.HashMap<String, String> named countryNames, which contains a list of country names indexed by ISO 3166 country code:

java.util.HashMap<String, String> countryNames = new java.util.HashMap<String, String>();
countryNames.put("AD", "Andorra");
countryNames.put("AE", "United Arab Emirates");
countryNames.put("AF", "Afghanistan");
countryNames.put("AG", "Antigua and Barbuda");
// ...

You wish to list the content of this map to System.out.

(The methods described here are not specific to HashMap and can be applied to any type of Map.)


A common method for iterating over a Java collection is to use an enhanced for loop, which has the form:

for (element: collection) statement

collection is the collection to be iterated over, statement is a statement to be executed for each entry in the collection, and element is a variable used to refer to the current element while the iteration is in progress.

This technique is applicable to implementations of java.util.Collection, other types of java.lang.Iterable, and to built-in arrays. A Map is none of these, so cannot directly be used as the subject of an enhanced for loop. However it does provide a method named entrySet, which returns a view of the Map in the form of a Set of Map.Entry.

A Set is a type of Collection, so can be used in an enhanced for loop. Each Map.Entry visited by the loop contains one of the keys from the map and the corresponding value. These can be extracted from the Map.Entry using its getKey and getValue methods respectively:

for (Map.Entry<String, String> entry: countryNames.entrySet()) {
  System.out.printf("%s: %s\n", entry.getKey(), entry.getValue());

Be aware that:

This method is applicable when writing for Java 5 or higher.


Using an Iterator

An alternative to the enhanced for-loop used above is to explicitly declare an iterator, then repeatedly advance it until all entries in the map have been visited:

for (Iterator<Map.Entry<String, String>> it = countryNames.entrySet().iterator(); it.hasNext(); ) {
  Map.Entry<String, String> entry = it.next();
  System.out.printf("%s: %s\n", entry.getKey(), entry.getValue());

This method adds some clutter to the code, and it was precisely to avoid such clutter that enhanced for-loops were introduced into Java. However, it does have the potential benefit of allowing access to the iterator from within the loop body. Such access is important if you want to delete entries from the map while iterating, because the only safe way to do that is by means of the Iterator.remove method:

for (Iterator<Map.Entry<String, String>> it = countryNames.entrySet().iterator(); it.hasNext(); ) {
  Map.Entry<String, String> entry = it.next();
  if (shouldBeRemoved(entry)) {

There is no good reason why use of an enhanced for-loop should result in better or worse performance than an explicitly declared iterator, since the former is merely a syntactic convenience for expressing the latter. When compared using the Java SE 8 compiler, they were found to result in identical bytecode.

Using a lambda expression

A lambda expression in Java is a type of object which behaves as an anonymous method. For example, the following lambda expression provides the same functionality as the body of the enhanced for-loop used in the method above:

(String key, String value) -> System.out.printf("%s: %s\n", key, value)

The expression takes two arguments, and is suitable for passing to Map.forEach. Doing so causes the lambda expression to be invoked for each key-value pair in the map:

countryNames.forEach((key, value) -> System.out.printf("%s: %s\n", key, value));

The output produced by this method should be the same as the others described above, however the implied method is quite different and it should not be considered an equivalent. Whether it is a better method will depend on the circumstances, and is to some extent a matter of opinion:

Further Reading

Tags: java