Home Java Java-tips Data Collections Maps Java: Map Iteration

Ask Questions?

View Latest Questions

Advertisement


 
 

Java: Map Iteration
Posted on: July 26, 2006 at 12:00 AM
No direct iteration over Maps -- Get Set of keys or key-value pairs from Mapt

Java: Map Iteration

No direct iteration over Maps -- Get Set of keys or key-value pairs from Mapt

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.

Order of map elements in iteration

The order of the elements obtained from a Map depends on the type of Map they came from.

TreeMap
The elements are ordered by key.
HashMap
The elements will be in an unpredictable, "chaotic", order.
LinkedHashMap
The elements will be ordered by entry order or last reference order, depending on the type of LinkedHashMap.

Example - Iterating over the "entry set"

This example utility method prints the key-value pairs in a map. This utility method is designed to work for all Maps, so it isn't able to take advantage of generics.

//============================================ utility method dumpMap
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());
    }
}

Example

See Example - WordFrequency for an example of a different way to go over a HashMap by converting it to an ArrayList.

Advertisement


DMCA.com