Tags

Feb 22, 2012

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.

Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.

Map map = new HashMap();
for (Map.Entry entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using For-Each loop.
Map map = new HashMap();

//iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

//iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}
This method gives slight performance advantage over entrySet iteration and is more clean.

Method #3: Iterating using Iterator.

Map map = new HashMap();
Iterator> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}
f you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.

No comments:

Post a Comment