HashMap is one of the data structure in Java which implements the Map Interface. It makes use of the key value pair to store the data. Following are the four ways to iterate Java HashMap. The same approach can be used for iterating over other Map implementations like HashTable, TreeMap, etc.
1. Using Lambda Expression
Lambda Expressions were introduced as part of Java 8 and it is the easiest option to iterate the HashMap.
Map<String,Integer> map = new HashMap<String,Integer>(); map.put("Robert", 34); map.put("Kiran", 29); map.put("Andy", 44); map.forEach((key,value) -> { System.out.println(key); System.out.println(value); });
2. Using entrySet & advanced for loop
Map<String,Integer> map = new HashMap<String,Integer>(); map.put("Robert", 34); map.put("Kiran", 29); map.put("Andy", 44); for(Map.Entry<String,Integer> entry : map.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue()); }
Also Read: How to Generate MD5 Hash in Java
3. Using keySet & advanced for loop
Map<String,Integer> map = new HashMap<String,Integer>(); map.put("Robert", 34); map.put("Kiran", 29); map.put("Andy", 44); for(String key : map.keySet()) { System.out.println(key); System.out.println(map.get(key)); }
4. Using Iterator interface
Map<String,Integer> map = new HashMap<String,Integer>(); map.put("Robert", 34); map.put("Kiran", 29); map.put("Andy", 44); for(String key : map.keySet()) { System.out.println(key); System.out.println(map.get(key)); }