Iteration over Java Map elements


Map implementations are very useful structures for storing key -> value associations. Mostly they are used for getting the value associated with specific key. But sometimes we want to enumerate all elements in the map. Below are a few examples of doing this. Let's assume we have this Map

Map<String, String> countryCodes = new HashMap<String, String>();
countryCodes.put("Bulgaria", "bg");
countryCodes.put("India", "in");
countryCodes.put("Germany", "de");

Iteration over map keys
 


To iterate over all map keys use the following construction:

Iterator<String> countryIterator = countryCodes.keySet().iterator();
while (countryIterator.hasNext()) {
    String code = countryIterator.next();
    System.out.println(code);
}

This produces the following result:

Bulgaria
Germany
India

Note that the order is different than we defined since HashMap is used. This implementation uses hashCode() to distribute keys, so it basically produces random ordered keys.


Iteration over values
 


Enumerating all map values is done in a very similar fashion:

Iterator<String> codeIterator = countryCodes.values().iterator();
while (codeIterator.hasNext()) {
    String code = codeIterator.next();
    System.out.println(code);
}


Output here is:

bg
de
in


Iteration over both map content
 


Now let's merge both examples - print all map keys with their associated values. Here's how it's done with slight modification of the first example:

Iterator<String> countryIterator1 = countryCodes.keySet().iterator();
while (countryIterator1.hasNext()) {
    String country = countryIterator1.next();
    System.out.println(country + ": " + countryCodes.get(country));
}


The output is as we expected:

Bulgaria: bg
Germany: de
India: in

       
However if you examine the code further you'll notice that you're doing one map lookup for each printed line. Our map is relatively small one, but in case of large datasets this could be a slow down. To optimize this, use the following construct:

Iterator<Map.Entry<String, String>> mapIterator = countryCodes.entrySet().iterator();
while (mapIterator.hasNext()) {
    Map.Entry<String, String> entry = mapIterator.next();
    System.out.println(entry.getKey() + ": " + entry.getValue());
}   


Of course the result is the same here.
 

 

Comments:

Ashok (18-12-2012 09:24) :
Good Example

Few more ways (13-08-2013 05:32) :
http://javarevisited.blogspot.com/2011/12/how-to-traverse-or-loop-hashmap-in-java.html

Back to articles list

This page was last modified on 2024-12-05 20:03:46