How to iterate over a HashMap in java
There is no direct method using which we can iterate over a hash map. Thus, we do it differently.
First, we have to visualize our map as a set and get a set view of the map.
Once we have the set, we can iterate either using an iterator or using the enhanced for loop.
The below diagram help us visualize the same.
So, if we have a map like below
Map<Integer, String> map = new HashMap<>();
To get the set view of this map, we need to call the entrySet() method on map object like below
Set<Entry<Integer, String>> setViewOfMap = map.entrySet();
Below is the full example
package com.sks;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class HashMapExample {
public static void main(String[] args) {
Map<Integer, String> scientistMap = new HashMap<>();
scientistMap.put(101, "CV Raman");
scientistMap.put(102, "Einstein");
scientistMap.put(103, "Newton");
scientistMap.put(104, "APJ Abdul Kalam");
scientistMap.put(105, "Darwin");
Set<Entry<Integer, String>> setViewOfMap = scientistMap.entrySet();
for(Entry<Integer, String> entry : setViewOfMap) {
System.out.println("Key = " + entry.getKey() + " : " + "Value = " + entry.getValue());
}
}
}
Output: