Friday, March 27, 2020

Best Trend To Iterate Over Each Entry Of Hashmap Inward Java

What is the best way to Iterate over HashMap inwards Java? too non only HashMap, but whatever Map implementation including onetime Hashtable, TreeMap, LinkedHashMap too relatively newer ConcurrentHashMap, is a ofttimes asked enquiry from Java Programmers, amongst only about sense nether his belt. Well, when it comes to choosing betwixt different ways to iterate over Map inwards Java, it's y'all need, which plays an of import role. For example, if y'all only desire to iterate over each entry of HashMap, without modifying Map, too thus iterating over entry ready using Java 1.5 foreach loop seems the most elegant solution to me. The reason, it only 2 lines of code using a foreach loop too Generics, too past times getting the ready of entries, nosotros teach telephone substitution too value together, without farther searching inwards HashMap. This makes it too the fastest way to loop over HashMap inwards Java. 


On the other hand, if y'all desire to withdraw entries, spell iterating over HashMap, may travel alone selective entries, than foreach loop volition non help. Though foreach loop internally uses Iterator for traversing elements, It doesn't reveal handgrip to that Iterator, which way y'all alone stimulate got remove() method of Map to withdraw entries. That's non the ideal way, particularly if y'all had to withdraw lot of entries too that to during Iteration. 

Your Iterator may too throw ConcurrentModificationException, depending upon it's fail-safe or fail-fast Iterator. E.g. Iterator of ConcurrentHashMap are weekly consistent amongst actual Map too doesn't throw ConcurrentModificationException

This leaves us amongst traditional spell loop too Iterator combo, for looping HashMap using Map.entrySet() too removing entries.



Best way to Iterate over HashMap inwards Java

Here is the code event of Iterating over whatever Map flat inwards Java e.g. Hashtable or LinkedHashMap. Though I stimulate got used HashMap for iteration purpose, y'all tin apply same technique to other Map implementations. Since nosotros are alone using methods from java.uti.Map interface, solution is extensible to all kinds of Map inwards Java. We volition utilization Java 1.5 foreach loop too Iterating over each Map.Entry object, which nosotros teach past times calling Map.entrySet() method. Remember to utilization Generics, to avoid type casting. Use of Generics too foreach loop result inwards really concise too elegant code, equally shown below.


for(Map.Entry<Integer, String> entry : map.entrySet()){     System.out.printf("Key : %s too Value: %s %n", entry.getKey(), entry.getValue()); }
 
This code snippet is really handy for iterating HashMap, but has only 1 drawback, y'all tin non withdraw entries without risking ConcurrentModificationException. In side past times side section, nosotros volition come across code using Iterator, which tin assist y'all for removal of entries from Map.



Removing Entries from Map inwards Java

One argue for iterating over Map is removing selected telephone substitution value pairs from Map. This is a full general Map requirement too holds truthful for whatever form of Map e.g. HashMap, Hashtable, LinkedHashMap or fifty-fifty relatively novel ConcurrentHashMap. When nosotros utilization foreach loop, it internally translated into Iterator code, but without explicit handgrip to Iterator, nosotros only tin non withdraw entries during Iteration. If y'all do,  your Iterator may throw ConcurrentModificationException. To avoid this, nosotros demand to utilization explicit Iterator too spell loop for traversal. We volition nonetheless utilization entrySet() for functioning reason, but nosotros volition utilization Iterator's remove() method for deleting entries from Map. Here code example  to withdraw telephone substitution values from HashMap inwards Java:

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

You tin see, nosotros are using remove() method from Iterator too non from java.util.Map, which accepts a telephone substitution object. This code is rubber from ConcurrentModificationException.



HashMap Iterator Example

By the way, hither is consummate code example, combining both approaches for iterating over HashMap inwards Java. As I said before, y'all tin utilization same code snippet to iterate whatever Map class, nosotros are non using whatever specific methods from HashMap, code is consummate based on Map interface.

import java.util.HashMap; import java.util.Iterator; import java.util.Map;  /**  *  * Best way to iterate over Map inwards Java, including whatever implementation e.g.  * HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap too Hashtable.  * Java 1.5 foreach loop is most elegant too combined amongst entry ready also  * gives best performance, but non suitable for removing entries, equally y'all don't have  * reference to internal Iterator.  *  * Only way to withdraw entries from Map without throwing ConcurrentModificationException  * is to utilization Iterator too spell loop.  *  * @author http://java67.blogspot.com  */ public class HashMapIteratorExample {      public static void main(String args[]) {               // Initializing HashMap amongst only about telephone substitution values         Map<Integer, String> map = new HashMap<Integer, String>();         map.put(1, "Core Java");         map.put(2, "Java SE");         map.put(3, "Java ME");         map.put(4, "Java EE");         map.put(5, "Java FX");                 // Iterate over HashMap using foreach loop         System.out.println("Java 1.5 foreach loop provides most elegant
                             way to iterate over HashMap inwards Java");         for(Map.Entry<Integer, String> entry : map.entrySet()){             System.out.printf("Key : %s too Value: %s %n", entry.getKey(),
                                                           entry.getValue());         }                 // Better way to loop over HashMap, if y'all desire to withdraw entry         System.out.println("Use Iterator too spell loop, if y'all want 
                              to withdraw entries from HashMap during iteration");         Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator();         while(iterator.hasNext()){             Map.Entry<Integer, String> entry = iterator.next();             System.out.printf("Key : %s too Value: %s %n", entry.getKey(), 
                                                           entry.getValue());             iterator.remove(); // correct way to withdraw entries from Map, 
                               // avoids ConcurrentModificationException         }     }        }  Output: Java 1.5 foreach loop provides most elegant way to iterate over HashMap inwards Java Key : 1 too Value: Core Java Key : 2 too Value: Java SE Key : 3 too Value: Java ME Key : 4 too Value: Java EE Key : 5 too Value: Java FX Use Iterator too while loop, if y'all desire to withdraw entries from HashMap during iteration Key : 1 too Value: Core Java Key : 2 too Value: Java SE Key : 3 too Value: Java ME Key : 4 too Value: Java EE Key : 5 too Value: Java FX

That's all close How to Iterator over HashMap inwards Java. We stimulate got seen twosome of ways to iterate over each entry, but equally I said, best way is to utilization foreach loop too entry set, if y'all only demand to traverse, without modifying actual Map. It's really elegant for filtering, where y'all demand to create only about other Map, from actual Map, based on only about filtering criterion. Since Map.Entry object holds both telephone substitution too value, it provides fastest access to them, instead of calling Map.get(key) method, which involves searching inwards Map.

Further Learning
Java In-Depth: Become a Complete Java Engineer
Difference betwixt ArrayList too LinkedList inwards Java

No comments:

Post a Comment