Java Program to Iterate over a HashMap

To understand this example, you should have the knowledge of the following Java programming topics:


In Java HashMap, we can iterate through its keys, values, and key/value mappings.

Example 1: Iterate through HashMap using the forEach loop

Output

HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}
Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI, 
Keys: Java, JavaScript, Python,
Values: Enterprise, Frontend, ML/AI,

In the above example, we have created a hashmap named languages. Here, we have used the forEach loop to iterate through the elements of the hashmap.

Notice that we are independently iterating through the keys, values, and key/value mappings.

Note: We have used the Map.Entry class. It is the nested class that returns a view of the map.


Example 2: Iterate through HashMap using iterator()

Output

HashMap: {Java=Enterprise, JavaScript=Frontend, Python=ML/AI}
Entries: Java=Enterprise, JavaScript=Frontend, Python=ML/AI, 
Keys: Java, JavaScript, Python,
Values: Enterprise, Frontend, ML/AI,

In the above example, we are iterating through keys, values, and key/value mappings of the hash map. We have used the iterator() method to iterate over the hashmap. Here,

  • hasNext() - returns true if there is next element in the hashmap
  • next() - returns the next element of the hashmap

Note: We can also use the HashMap forEach() method to iterate over the hashmap.