Sunday, 30 August 2015

Iterate over HashMap

Best way to Iterate over HashMap in Java

Here is the code example of Iterating over any Map class in Java e.g. Hashtable or LinkedHashMap. Though I have used HashMap for iteration purpose, you can apply same technique to other Map implementations. Since we are only using methods from java.uti.Map interface, solution is extensible to all kinds of Map in Java. We will use Java 1.5 foreach loop and Iterating over each Map.Entry object, which we get by calling Map.entrySet() method. Remember to use Generics, to avoid type casting. Use of Generics and foreach loop result in very concise and elegant code, as shown below.


for(Map.Entry<Integer, String> entry : map.entrySet()){
    System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
}

This code snippet is very handy for iterating HashMap, but has just one drawback, you can not remove entries without risking ConcurrentModificationException. In next section, we will see code using Iterator, which can help you for removal of entries from Map.



Removing Entries from Map in Java

One reason for iterating over Map is removing selected key value pairs from Map. This is a general Map requirement and holds true for any kind of Map e.g. HashMap, Hashtable, LinkedHashMap or even relatively new ConcurrentHashMap. When we use foreach loop, it internally translated into Iterator code, but without explicit handle to Iterator, we just can not remove entries during Iteration. If you do,  your Iterator may throw ConcurrentModificationException. To avoid this, we need to use explicit Iterator and while loop for traversal. We will still use entrySet() for performance reason, but we will use Iterator's remove() method for deleting entries from Map. Here code example  to remove key values from HashMap in Java:



  //code goes here
Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
   Map.Entry<Integer, String> entry = iterator.next();
   System.out.printf("Key : %s and Value: %s %n", entry.getKey(), entry.getValue());
   iterator.remove(); // right way to remove entries from Map,
                      // avoids ConcurrentModificationException
}


You can see, we are using remove() method from Iterator and not from java.util.Map, which accepts a key object. This code is safe from ConcurrentModificationException.


Read more: http://java67.blogspot.com/2013/08/best-way-to-iterate-over-each-entry-in.html#ixzz3kIiWUMZU

No comments:

Post a Comment