Sunday, September 6, 2009

How to iterate Map in java?

No direct iteration over Maps -- Get Set of keys or key-value pairs from Map to iterate.
Maps do not provide an iterator() method as do Lists and Sets. A Set of either keys (keySet()) or key-value Map.Entry elements (entrySet()) can be obtained from the Map, and one can iterate over that.

Example:

public static void dumpMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}

No comments:

Post a Comment