How to iterate a Map in Java
There are several ways to iterate a Map in java.
- Iterate Map using iterator
- Iterate Map using keySet.
- Iterate Map using Entry Object.
- Using Lamda Expression.
Example to iterate a Map.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
package com.code2succeed.collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class HashMapExample { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<Integer, String>(); map.put(1, "New York"); map.put(2, "London"); map.put(3, "Paris"); map.put(4, "Mumbai"); //Iterate HashMap using iterator Iterator<Entry<Integer, String>> iterator = map.entrySet().iterator(); System.out.println("Example 1"); while (iterator.hasNext()) { Map.Entry<Integer,String> entry = (Map.Entry<Integer,String>) iterator.next(); System.out.println("Key : " + entry.getKey() + " Value :" + entry.getValue()); } //Iterate using keySet. System.out.println("\nExample 2"); for (Object key : map.keySet()) { System.out.println("Key : " + key + " Value : " + map.get(key)); } //most efficient way. good to use if you are not using Java 8. System.out.println("\nExample 3"); for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue()); } //Java 8 only, forEach and Lambda. recommend! System.out.println("\nExample 4"); map.forEach((k,v)->System.out.println("Key : " + k + " Value : " + v)); } } |
Output
Example 1
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Example 2
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Example 3
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Key : 1 Value : New York
Key : 2 Value : London
Key : 3 Value : Paris
Key : 4 Value : Mumbai
Example 4
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai
Key : 1 Value :New York
Key : 2 Value :London
Key : 3 Value :Paris
Key : 4 Value :Mumbai