There are several ways of iterating over a Map in Java.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.
Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.
Method #2: Iterating over keys or values using For-Each loop.
Method #3: Iterating using Iterator.
following techniques will work for any map implementation HashMap, TreeMap, LinkedHashMap, Hashtable etc.
Method #1: Iterating over entries using For-Each loop.
This is the most common method and is preferable in most cases.
MapFor-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.map = new HashMap (); for (Map.Entry entry : map.entrySet()) { System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
Method #2: Iterating over keys or values using For-Each loop.
MapThis method gives slight performance advantage over entrySet iteration and is more clean.map = new HashMap (); //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); }
Method #3: Iterating using Iterator.
MapWithout Generics:map = new HashMap (); Iterator > entries = map.entrySet().iterator(); while (entries.hasNext()) { Map.Entry entry = entries.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); }
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); }f you need only keys or values from the map use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration you have to use method #3. Otherwise use method #1.
No comments:
Post a Comment