Sunday, July 28, 2013

How to Iterate Over a Map in Java

There are several ways of iterating over a Map in Java. Let see the common methods to iterate over Map.
Since all maps in Java implement Map interface, following techniques will work for any map implementation like HashMap, TreeMap, LinkedHashMap, Hashtable, etc.


1. This is the most common method and is preferable in most cases. Should be used if you need both map keys and values in the loop.


Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

You will get NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

2. Iterating over keys or values using For-Each loop.
If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.


//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);
}


Performance advantage over entrySet iteration

3. Iterating using Iterator

Using Generics:

Map<Float, Float> map = new HashMap<Float, Float>();
Iterator<Map.Entry<Float, Float>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Float, Float> 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);
}

- You can use this techinque to iterate over keySet or values like discussed in case 2.
- It is the only way to iterate over a map in older versions of Java.

- It is the only method that allows you to remove entries from the map during iteration by calling iterator.remove().
- In terms of performance this techniques is equivalent to for-each iteration.


4. Iterating over keys and searching for values - inefficient


Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

Alternative for method case 1- It is pretty slow and inefficient as getting values by a key might be time consuming


Other way :
for (Integer key : hm.keySet()) {
System.out.println("Key = " + key + " - " + map.get(key));
}


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

1 comment: