Skip to content

Iterate through Java HashMap Example

This example shows how to iterate through HashMap in Java including iterating over keys, values, and mappings of the HashMap using while loop, for loop and enhanced for loop.

How to iterate over Java HashMap?

We will use the example Employee class and store its objects into Java HashMap.

Let’s first store several Employee objects into the HashMap object.

We have put employee ID as the key and employee object as the value for each mapping stored in the HashMap.

1) Iterate through keys of the HashMap

Use this approach if you are interested only in keys stored in the HashMap. Use the keyset method of the HashMap class to get the Set view of the stored keys and for loop to iterate over the keys.

Output

2) Iterate through values of the HashMap

Use this approach if you are interested only in the values stored in the HashMap. Use the values method of the HashMap class to get the Collection view of the stored values and a for loop to iterate over the values.

Output

3) Iterate through keys and values of the HashMap

Use this approach if you are interested in retrieving both keys and values stored in the HashMap. Use the entrySet method of the HashMap to get the Set view of stored mappings in the form of Map.Entry object and use a for loop to iterate over the key-values.

Output

Important Note: If you are using Java version 1.4 or lower, the enhanced for each loop will not work since it was introduced in Java 1.5. Also, Generics was introduced in Java version 1.5. Use the following code to iterate through HashMap instead.

Using a while loop:

Using for loop:

Please also note that the HashMap does not guarantee the order of elements returned. That means the returned values might not be in the same order in which they are inserted (that is why you might see different output)

Also See: How to iterate through List in Java.

This example is a part of the Java HashMap tutorial.

Please let me know your views in the comments section.

About the author

Leave a Reply

Your email address will not be published.