Tuesday, November 29, 2011

Iterate over a Map(HashMap) in Java

Here are three methods of iterating through a Map(HashMap) in Java and their pros and cons. They all works for any map implementation in Java, e.g. HashMap, TreeMap, HashTable,LinkedHashMap.

Method #1
Iterating over Entries
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());
}
pros : You can get both keys and values via entrySet().
cons: NullPointerException will be thrown if you try to iterate over a null map. You should always check for null references before iterating.

Method #2
Iterating over either Key or Value Sets
Map<Integer, Integer> map = new HashMap<Integer, Integer>();

//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);
}
pros: If all you need is either key sets or value sets, this method is about 10% faster than iteration over entrySet(), and also cleaner.
cons: The same as above

Method #3
Iterating using Iterator
--With Generics
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> 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);
}
The same method can be used for obtaining the key and value sets respectively. Its performance is equal to for-each loop.
pros: It is the only way if you want to remove entries during iteration by implementing iterator.remove(). If you do this in for-each loop, you will get unpredictable results.
cons: Look a little redundant than other methods.

Method #4
Iterating over key sets and search 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);
}
Getting values by keys is inefficient and time-consuming, in different Maps it can be 20% to 200% slower than Method #1.

1 comment:

  1. I hope these methods to work on in solving the technical issues. However, thanks for sharing this useful blog. I am just convinced with your words for solution.

    ReplyDelete